Pergunta

Current HTML snippet:

<ul class="ShippingProviderList">
  <li>
    <label id="shippingMethod_500dae76abe48_0">
      <input id="shippingCheck_500dae76abe48" type="radio" value="0" name="selectedShippingMethod[500dae76abe48]" />
      <span class="ShipperName">My Own Shipping Account (Please make sure that account number is specified within your account page or item will not ship!)</span>
      <em class="ShipperPrice ProductPrice">$0.00</em>
    </label>
  </li>
  <li> 2nd option may or may not be here </li>
</ul>

Current Javascript snippet:

<script>
var radio = document.getElementById('shippingCheck_500d6aa9a300e'),
var input1 = document.getElementById('FormField_25'),
input2 = document.getElementById('FormField_26'),
btn = document.getElementById('ML20').getElementsByTagName('input')[0];

btn.onclick = function(e) {
if( radio.checked && input1.value.length >= 20 && input2.value.length >= 20 ) {
    alert('Please provide a Shipping Account Number in either the Billing or Shipping sections in order to use your own Shipping Account.');
    e.preventDefault(); // we all stop the submit from happening.
    e.stopPropagation();
    return false;
}
// otherwise do something or nothing and let the submit happen.
};
</script>

The problem is that the 500d shipping check is randomly generated, and I have no control over such. is it possible to adjust the Javascript to pull the proper data by say using the span class "ShipperName" that has the term My Own Shipping in it, then pull the input field before that? or is there a better way to do this that I am missing? I am not able to assign an ID, Class, or change the actual html generated there in any way.

Foi útil?

Solução

If jQuery is acceptable, you can use this:

$("input[id^='shippingCheck']")

Using normal Javascript, you can use this function:

function wildcard(startingId){
  // get all inputs
  var inputs = document.getElementsByTagName("input");
  // iterate over them
  for ( var i = 0; i < inputs.length; i++ ) {

    if ( inputs[i].nodeType === 1 ) {
      // id start with 'shippingCheck' ?
      if (inputs[i].id.indexOf(startingId) == 0)
      {
         return inputs[i];
      }
    }
  }
}

And call it like this:

wildcard("shippingCheck")


You can try this:

function fetchInput() {
    var input;
    $(".ShipperName").each(function() {
        if ($(this).text().indexOf("My Own Shipping Account") != -1)
        {
            input = $(this).prev().get(0);
            return;
        }
    });
    return input;
}

And call it like this:

fetchInput();

The function returns the DOM element, so you can access the id attribute, for example, like this:

var inputId = fetchInput().id;


You basically just want your radio variable to be a reference to the DOM element, right? So you would use this:

var radio = fetchInput();

Outras dicas

You can try this using jQuery:

var radio = $('[id^="shippingCheck"]');

This will find an element with an id that begins with the string "shippingCheck".

var spans = ​document.getElementsByTagName("span"),​​​​​​ span, i, len, node;

​for (i = 0, len = spans.length; i < len; i++) {
    span = spans[i];
    if (span.innerHTML.match(/My Own Shipping/)) {
        node = span;
        while (node && node.nodeName !== "INPUT") {
            node = node.previousSibling;
        }
        console.log(node);  // This is the input element before that SPAN.
        break;        
    }
}

A DOM traversal library would make that much simpler.​​ For instance, with jQuery:

console.log($("span:contains(My Own Shipping)").prev("input")[0]);

Try this instead:

var radio = $('.ShipperName:contains("My Own Shipping")').siblings(':radio');

It will find a radio button next to a .ShipperName that contains "My Own Shipping".

If you want to get the previous element by pure javascript, you can use the previousSibling property with some checking, like the function below. The parameter n is the span element in your case.

function getPreviousSibling(n) {
    var x = n.previousSibling;
    while (x.nodeType != 1) { // check if it's an element node
        x = x.previousSibling;
    }
    return x;
}

However, if you get the previous input element of the span with class 'ShipperName', you will get more than one radio inputs (because you might have more than one item in the list). You still need to do extra stuff the get the one you want, but at least you can use the id of the radio input and do something with it.

See the example here.

It would be easier to select elements if you use jQuery.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top