Change dropdown value with jQuery

<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
    <option value="">Choose Make</option>
    <option value="2063">Acura</option>
    <option value="2064">Honda</option>
</select>

I have a drop down list. I read the href attribute of the link and assigned it as a value for the drop down list. but I want to take only the number from the link and assign it as a value for the drop-down list of how I can do this.

<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
    <option value="">Choose Make</option>
    <option value="http://store.teknotik.com/category-s/2063.htm">Acura</option>
    <option value="http://store.teknotik.com/category-s/2064.htm">Honda</option>
</select>

I used the following jquery to get the link as value

$("#data a").each(function(index) {
        if ($(this).attr("class") == "subcategory_link") {


            //document.getElementsById("year").innerHTML="<option value="+$(this).attr("href")+">test</option>";
            lnk[cnt] = $(this).attr("href");
            cnt = cnt + 1;
            //alert($(this).attr("href"));

        }
    });

but I want the dropdown to be:

<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
    <option value="">Choose Make</option>
    <option value="2063">Acura</option>
    <option value="2064">Honda</option>
</select>

I want to have only the number before .htm in the above dropdownho send as value. Please inform.

+3
source share
5 answers

A simple way:

$('#vehicle_make option[value!=""]').each(function() {
    this.value = this.value.replace(/\D/g, "");
});​

Live demo


\d // Numerical char
\D // Not numerical char <===
g  // Is a flag which means find all the occurrences, and not only the first.

Great regex cheat sheet.

So, I search for all non-numeric characters (c \D) and “replace” them with an empty string.

+3
source

.replace('', '')

.replace('http://store.teknotik.com/category-s/','').replace('.htm','')

0

, : :

lnk[cnt] = $(this).attr('href').substring($(this).attr('href').lastIndexOf('/')+1);
lnk[cnt]=lnk[cnt].replace('.htm','');

( , )

Then set the value:

$("#vehicle_make").val(lnk[cnt])
0
source

You can find it below:

var url = $(this).attr("href");
var urlTemp1 = url.split("/");
var urlTemp2 = (urlTemp1[urlTemp1.length -1]).split(".");
var yourNumber = urlTemp2[0];
alert(yourNumber);
0
source

Try:


$(document).ready(function() {
  $("select[name='vehicle_make'] option[value!='']").each(function() {
     this.value = this.value.split("/").pop().split(".")[0];
  });
});

Hope this helps

0
source

All Articles