this is my code of a dynamic drop down menu and I want to change the text of the first option which has no id and the value is empty!
this is the code:
<div class="my-tours">
<select name="tours">
<option value="">All</option>
<option value="america">America</option>
</select>
</div>
Your question is not clear what you want as output. but you change first option value by doing something like this :
$("#select-id option:first").attr("value", "");
$('#tours > option:not([id])').filter(function () { let val = $(this).attr('value'); return val === undefined || val === ''; }).first().text('First id-less with no value');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my-tours"> <select name="tours" id="tours"> <option value="mexico">Mexico</option> <option value="">All</option> <option value="america">America</option> <option>Nowhere</option> </select> </div>
I added an id to the <select>
tag to make it simpler to select it, and make DOM queries for it more efficient. I highly recommend doing that, but if for some reason you can't add an id, you could also select it using $('select[name="tours"]')
.
Step by step, here is what this does:
$('#tours > option:not([id])')
selects all of the <option>
tags inside of #tours
that do not have an id
attribute. .filter('[value=""]')
instead. .first()
grabs the first option that matched our filter. .text()
sets the new text. Here it is. Use name
attribute and :first
in option selector.
$(document).ready(function() { $("select[name='tours'] option:first").text("wow"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my-tours"> <select name="tours"> <option value="">All</option> <option value="america">America</option> </select> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.