Reputation: 35
folks! I saw jQuery for the first time! Please suggest. I have several forms with [select] elements.
<form action="/configuration.html" class="settings">
TEST_MODE:
<select name="value" class="value">
<option value=null></option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
<input type="hidden" name="setting" value="TEST_MODE" />
<input type="submit" value="Save" />
</form>
<form action="/configuration.html" class="settings">
USE_DNS:
<select name="value" class="value">
<option value=null></option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
<input type="hidden" name="setting" value="USE_DNS" />
<input type="submit" value="Save" />
</form>
I'm just trying to fill select elements with values taken from server on load.
$(".settings").ready(function() {
var $form = $(this),
settingName = $form.find("input[name='setting']").val(),
selectObject = $form.find("select[name='value']");
var rnd = Math.random(100);
$.get("/configuration.html=read", {"setting":settingName, "rnd":rnd})
.done(function(data) {
selectObject.val(data);
})
.fail(function() {
alert("No answer from server!");
});
});
And I've a problem here. Code is performed only for first form. I see that in server's logs. What should be done to done the same thing for second form too? And how correctly bind to 'select' element in this part:
selectObject = $form.find("select[name='value']");
Thank you in advance!
Upvotes: 2
Views: 78
Reputation: 35
Solution that works for me:
$(".settings").each(function() {
var settingName = $(this).find("input[name='setting']").val();
var selectObject = $(this).find("select");
var rnd = Math.random(100);
$.get("/configuration/read", {"setting":settingName, "rnd":rnd})
.done(function(data) {
selectObject.find("[value='" + data + "']").attr("selected", "selected");
})
.fail(function() {
alert("No answer from server!");
});
});
Upvotes: 0
Reputation: 72865
selectObject = $form.find("select[name='value']");
You can not do it this way, because you are querying for multiple objects when using $form.find
. If you do console.log(selectObject)
you will be able to see the output from this selection in your console, and thus see why it won't work.
You would need to use each()
to iterate through all of them and update the values:
$(".settings select[name='value']").each(function() {
$(this).val(data);
});
Edit: I'm not 100% sure that selector will work, you may need to play with it.
Upvotes: 2