Skip to content Skip to sidebar Skip to footer

Stop Dropdown From Redirecting To Homepage

sI am using the following code to remove text starting from the '+' character from dropdown menu choices: $('select').each(function(){ var $wrapper=$(this); var $options=$wrap

Solution 1:

Following the jquery spirit "write less, do more" you could also do the text replacement operation like this:

$("select.cars option").each(function(){
 with ($(this)) {
  text(text().split("+")[0].trim());
  val(val().split("+")[0].trim());
 }
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectclass="cars"><optionvalue="Audi">Audi</option><optionvalue="BMW">BMW</option><optionvalue="Mercedes + Trailer">Mercedes + Trailer</option></select>

To limit the effect of the script on the selects you want to change and protect all the others I also added the class "cars" into the picture. Maybe something along those lines can be helpful for your project?

But this will not touch your current problem, that you leave the current page as soon as a select option has been selected. I suspect there must be another piece of (as yet unpublished) script that is responsible for that behaviour.

Solution 2:

You just need to add value to newly created option.

Try this:

$("select").each(function(){
  var $wrapper=$(this);
  var $options=$wrapper.find("option");
  $(this).empty();
  $options.each(function(index){
      var text = $(this).text().split("+")[0].trim();
      var newOption = newOption(text);
      // get value from previous option 
      newOption.value= $(this).val();
      $wrapper.append(newOption)
  })
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select><optionvalue="Audi">Audi</option><optionvalue="BMW">BMW</option><optionvalue="Mercedes + Trailer">Mercedes + Trailer</option></select>

Solution 3:

So this works!

$("select option").each(function(){
 with ($(this)) text(text().split("+")[0].trim());
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectclass="cars"><optionvalue="Audi">Audi</option><optionvalue="BMW">BMW</option><optionvalue="Mercedes + Trailer">Mercedes + Trailer</option></select>

Post a Comment for "Stop Dropdown From Redirecting To Homepage"