I'm sure this is relatively easy and straightforward, but I'm having no success figuring it out.
I am trying to set the selected option of a drop down list element using the following code:
if ($(this).attr("tagName") == "SELECT") {
oldValue = $(this).parent().parent().find('span.displayField').text();
$(this).val(oldValue).attr("selected", "selected");
return;
}
But it is not changing the select element at all. The code is definitely running, and oldValue is being populated appropriately.
Can anyone see what I might be missing?
Thanks!
UPDATE:
For clarification, here is the HTML:
<span class="displayField">Pending</span>
<span class="editField">
<select data-val="true" data-val-number="The field ProgramStatusId must be a number." data-val-required="The ProgramStatusId field is required." id="ProgramListViewModels_0__ProgramStatusId" name="ProgramListViewModels[0].ProgramStatusId">
<option value="1">Pending</option>
<option value="2">Tabled</option>
<option value="3">Approved</option>
<option value="4">Declined</option>
</select>
</span>
$(this).val(oldValue) will set the value of this to oldValue, and you just wanna find options with that texy. You want to use :contains() for this.
if ($(this).is('select')) {
oldValue = $(this).parent().parent().find('span.displayField').text();
$('option:contains('+oldValue+')', this).attr("selected", "selected");
return;
}
Or if there are multiple options that contain the text, but are different, try this:
if ($(this).is('select')) {
oldValue = $(this).parent().parent().find('span.displayField').text();
$('option', this).filter(function(){
return this.text === oldValue;
}).attr("selected", "selected");
return;
}
If I Understand your snippet correctly. I believe what you're trying to do is select the item with the same text() as $('span.displayField').
if ($(this).attr('tagName') == 'SELECT') {
// unselect previously selected element first.
var prev = $(this).find('option:selected').attr('selected', false);
// select item with text from span.displayField
var oldText = $(this).parent().parent().find('span.displayField').text();
var oldOption = $(this).find('option[text="' + oldText + '"]');
oldOption.attr('selected', true);
}
I dont understand what is that
).parent().parent().
if you just want to set select box value selected try these
http://api.jquery.com/val/
$('select.foo option:selected').val(); // get the value from a dropdown select
$('select.foo').val(); // get the value from a dropdown select
Related
I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
});
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.
I do have a form with a variable amount of dropdowns I want to check, if something is selected before submit.
What I have is this javascript, but it works for the 1st dropdown only.
var ddl = document.getElementById("status");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "")
{
alert("Machine status must be selected");
return false;
}
for this dropdown (this comes from a loop so I have a variable amount of them within the form)
<select name="mstatus[]" id="status">
<option value="">please select</option>
<option value="status1">ok</option>
<option value="status2">not ok</option>
</select>
Any hint in the right direction, much appreciated. thanks
I would suggest giving the selects you wish to iterate through the same class and use Jquerys .each(). https://api.jquery.com/each/
For the validation I would use a data tag to help you with the alert label
<select class="form-select" data-label="Machine status"></select>
Then the JS code
$('.form-select').each(function(index, element) {
let value = $(element).val();
let label = $(element).data("label");
if (value === "") {
alert(`${label} status must be selected`);
return false;
}
});
Without Jquery you could do.
document.querySelectorAll('.form-select').forEach(function (element, index) {
//do same code here
});
I want to check that all dropdown on page have select value or not?
fox Ex:-
<select id="#model.Id">
<option value="0">---</option>
<option value="1">abc</option>
<option value="2">xyz</option>
</select>
<select id="#model.Id">
<option value="0">---</option>
<option value="14">abc</option>
<option value="25">xyz</option>
</select>
Both are not same page and and issue there is dynamic id and name are assign to both of dropdrop down so i can't use jQuery by id or name and get selected value, not i want to check that both have selected value by Javascript or jQuery?
How can I do this?
Regards,
Vinit
Try this : you can iterate all select boxes on page using .each() and compare it's value with 0. If select value is 0 it means it is not selected otherwise selected.
$(function(){
$('select').each(function(){
var value = $(this).val();
var id = $(this).attr('id');
if(value==0)
alert('this dropdown has no selected value, id = '+id);
else
alert('this dropdown has selected value, id = '+id);
}):
});
Edit - as OP want to check if both dropdowns selected then show button otherwise hide it, use below code
$(function(){
$('select').change(function(){
var totalUnselectedDropdown = $('select option[value="0"]:selected').length;
if(totalUnselectedDropdown==0)
{
// enable button
$('#buttonId').prop('disabled',false);
}
else
{
// disable button
$('#buttonId').prop('disabled',true);
}
}):
});
you can do it this way:
$("select").each(function(){
alert($(this).val()) // will alert selected option value attribute value
if($(this).val() > 0) // value greater than 0 means value selected
{
alert("Value Selected")
}
})
Try this :
$("select").each(function(){
if(parseInt($(this).val()) > 0){
//all select have selected value
}
else
{
//any one/all select have not selected value
return false;
}
});
I am trying to validate a form.
What I am trying to do is validate the form by validating the Option display text not the option value, since the option values are int
Example:
<option value="selectcard">Please select</option>
If user clicks submit the form should validate if the option display says Please Select
regardless of what the option value is.
Code which is not working
function fun(){
$('#cardtype').change(function () {
var sel = $('option:selected', this).text();
if (sel == "Please select") {
$('.showotherpDescription').show();
} else {
}
});
}
Not working: http://jsfiddle.net/f5hxpo7g/2/
Also including the regular working example for validating the form based on option value
Validates Based on option value http://jsfiddle.net/f5hxpo7g/1/
Please let me know what i am doing wrong.
Thanks in advance.
Your function should be like this:
function fun()
{
var ddl = document.getElementById("cardtype");
var valor = ddl.options[ddl.selectedIndex].text;
if (valor == "--- Please select ---")
{
alert("Please select a card type");
}
}
Working fiddle:http://jsfiddle.net/robertrozas/XFtBD/169/
I fixed it, you should use this JS:
$(function () {
$('#subbutton').click(function () {
if ($('#cardtype option:selected').text() === "Please select")
{
alert("PLEASE SELECT");
}
});
});
And remove onclick="..." from the button, you don't need it. Also add id="subbutton.
Here's the working JSFiddle.
I checked out the jsfiddle you referenced and modified it slightly to make it work, you can see it here.
The issue with the code you provided is, IMO:
An issue with the purpose of your function (validation) and the event you're subscribing the code to (the combo selection changed event)
The way you're obtaining the text from the currently selected option, you should create the selector based on the element that contains the options, otherwise, if you have more than 1 combo in your page, you will get lots of values (one for each selected option).
Check out the code in the jsfiddle i provided and let me know if you need more information.
For reference, here is the code i used:
HTML:
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select>
<input type="button" onclick="fun()" value="click here">
JS:
function fun(){
var cmb = document.getElementById('cardtype');
var sel = cmb.options[cmb.selectedIndex].text;
if (sel == "--- Please select ---") {
alert('Please select a different option');
//$('.showotherpDescription').show();
} else {
}
}
}
I have a select box like so:
<select id="update_type_picker" name="update_type_picker">
<option value="play">Played</option>
<option value="play">playing</option>
<option value="want">Want</option>
<option value="rating">Rate</option>
</select>
And an input like this:
<input id="playing" name="playing" type="hidden">
And I'm trying to make this jquery work:
$(document).ready(function () {
$("select#update_type_picker").change( function() {
var text = this.text;
if (text = "playing") {
$("input#playing").attr('value', '1');
} else {
$("input#playing").attr('value', '');
}
});
});
I need to use text (not value) because two of the values are the same. With the jquery above the input value changes to 1 regardless of which option I choose. How can I make this work they way I need it to? Thanks!
You have to use:
var text = $(this).find("option:selected").text();
And as mentioned in a comment, you have to use == or === to compare strings in the if, not =.