user1996597
user1996597

Reputation: 1

on document load and if select option changed replace "select text"

I have a client that wants to have multiple distribution points, 1 located on the east coast and 1 located on the west coast

The ecommerce solution I use does not support this. I figured out a work around by having multiple shipping options using the ship from postcode as a key.

I used some jQuery to change the "shipping option" to reflect the distribution location.

The idea works but my weakness is the jquery, if the user changes the shipping option a second time the options default back to the original ecommerce default options .

the code so far is

jQuery(function($){ 
    var sel = document.getElementById('ShippingOptions');

    for(var i = sel.options.length - 1; i >= 0; i--) {
        if(sel.options[i].value == "-1")
            sel.options[i].text = "Select postage";
        if(sel.options[i].value == "75554")
            sel.options[i].text = "East Coast Distribution";
        if(sel.options[i].value == "75555")
            sel.options[i].text = "West Coast Distribution";

        $('#shippingSpan').text("Select postage");
    }
});

Upvotes: 0

Views: 235

Answers (2)

mplungjan
mplungjan

Reputation: 178402

Please do not mix jQuery and DOM.

It is not a great idea to change the select on the fly. Instead have two selects or a hidden field that can be updated with the correct shipping.

What is the trigger for the change of distribution points?

And why is it an issue? If the user chooses the option with value 75554, is the text not East Coast and if he chooses 75555 is the text of the option not West Coast?

I am guessing (from the question and code provided) this is what you might want:

DEMO

 var shippingOpts = { "75554":"East Coast Distribution", "75555":"West Coast Distribution" }

$(function() {    
  $('#ShippingOptions').on("change",function() {
    var val = $(this).val();
    $('#shippingSpan' ).text(
      (shippingOpts[val]) ? 
       shippingOpts[val] : 
       $("#ShippingOptions option:selected").text()
    );
  });

  // when page loads:
  $('#ShippingOptions').trigger("change");
});

Upvotes: 1

CRM
CRM

Reputation: 11

You can use jquery like this.

    $('#selectorid option:selected').each(function(i, item){
      // $(this).value() to access value 
      // $(this).text() to access text
      // $(this).value(" set value here "); same way for text

      // use if else ladder or switch case 

     });

Upvotes: 0

Related Questions