jQuery function is resetting dropdown selection - javascript

I have a drop-down menu in my page, it's something like this:
<select id="my_dropdown" name="my_dropdown">
<option value="one">ONE</option>
<option value="two">TWO</option>
<option value="three">THREE</option>
</select>
<input type="text" size="10" id="foobar" value="0" />
And my jQuery code is:
$('#foobar').keyup(function(){
notOptionOne();
}
function notOptionOne() {
if ( !$('#my_dropdown').val('one') ) {
alert('Option ONE was not selected');
}
}
No matter what is the selection on my dropdown, when I enter any text on the input box, it will show up the alert box and will reset my dropdown selection back to one. I want to keep my selection on where I leave when I close the alert box or do anything else. What is causing this behaviour?

function notOptionOne() {
if ( $('#my_dropdown').val()!='one' ) {
alert('Option ONE was not selected');
}
}
The val() function in jQuery can both get a value or set a value. when you pass a parameter to it, what jQuery do is to set the value of the control. If no parameter, get value.

Try this:
$('#my_dropdown').val() !== 'one'
$('#my_dropdown').val('one') is jquery wrapper, array-like object. That is why !$('#my_dropdown').val('one') is always false and you don't get an alert.

$('#my_dropdown').val('one') will set #my_dropdown's value as one (even in if construction).
You should get the value of #my_dropdown element and compare it with string one:
function notOptionOne() {
if ($('#my_dropdown').val() != "one") {
alert('Option ONE was not selected');
}
}

try this:
$('#my_dropdown').change(function(){
if ($(this).val() != 'one') {
alert('Option ONE was not selected');
}
})

Related

How do you populate an option value using jQuery?

I am trying to populate a form option value if it's attribute quantity equals zero.
My goal is to add the a message to the current option value
My html is:
<select class="valid">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
So far I've tried the following in jQuery but it's not working:
if($(this).attr('quantity') == '0') {
$(this).append('<span>message</span>');
}
If you don't care about preserving the original message, than you can simply say $(this).text("message"). Leave out the <span> since it cannot be rendered inside of an <option> element anyway.
if($(this).attr('quantity') == '0') {
$(this).text('message');
}
If you want to preserve the original message, you have a couple options. One would simply be to append the new message to the original, however, it may get tricky to remove it later, so I would suggest having some sort of delimiter so you can easily identify the original vs the appended message, like so:
var $option = $(this);
if($option.attr('quantity') == '0') {
$option.text($option.text().trim() + ' (message)');
}
Then, to remove the message, you can do something like this:
$option.text($option.text().slice(0, $option.text().indexOf('(')).trim());
You can populate the option with like this,
$(document).ready(function () {
$('.valid').on('change', function () {
if ($(this.options[this.selectedIndex]).attr('quantity') == 0) {
$(this.options[this.selectedIndex]).find('span').remove();
$(this.options[this.selectedIndex]).append('<span>Message</span>')
}
});
});
JSFIDDLE
I'm not entirely sure of what you're trying to achieve from your question, but you cannot add html elements to an option element. You can however change the text as follows:
$(document).on('change', '.valid', function(){
var selected = $('.valid > option:selected');
if(selected.attr('quantity') == '0'){
selected.text('something else');
}
});
if you wanted to append an error you could do so by using jQuery append() or concatenating with the original value. Alternatively if you wanted it as validation outside of the select box, you could simply assign to the value of a div by replacing the line inside of the if statement.
<select class="valid" onchange="quality(this.options[this.selectedIndex].getAttribute('quantity'));">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
<span id="msg"></span>
<script type="text/javascript">
function quality(val) {
if(parseInt(val) == 0){
document.getElementById("msg").innerHTML = "Message";
}
}

Select Drop down Form Validation (Display text)

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 {
}
}
}

jQuery: If user changes select to specific option then change different input value

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 =.

How to change text of specific option in a dropdown list?

I have a dropdown list,
<select id="bi_tool_y_axis" name="bi_tool[y_axis]">
<option value="0">Vote Count</option>
<option selected="selected" value="1">Choices of Poll</option>
<option value="2">Location</option>
</select>
and a jquery function to change option text of value 2 in the above dropdown list
function change_text_of_value_2(new_text){
// I want to change text "Location" with new_text in the dropdown list
}
How can I do this? Please help..
why not simply
$("#bi_tool_y_axis option[value='2']").text("anything else");
And this you call into function (your function and put the parameter into text function);
Or
function change_text(optionValue, new_text){
$("#bi_tool_y_axis option[value='"+optionValue+"']").text(new_text);
}
try this
function change_text_of_value_2(new_text){
$("#bi_tool_y_axis option[value='2']").text(new_text);
}
Try this
$(function() {
$('#bi_tool_y_axis').on('change', function() {
if ($(this).val() == '2') {
change_text_of_value_2($(this), "New_Text_Added")
}
});
});
function change_text_of_value_2($elem, new_text) {
$elem.find("option[value='2']").text(new_text);
}​
Check FIDDLE

Select-box control with jquery

I am using a selectbox:
<select name="priority" id="priority">
<option value="4">Low</option>
<option value="3" selected="selected">Normal</option>
<option value="2">High</option>
<option value="1">Emergency</option>
</select>
When user select "Emergency", then a confirmation box opens and if user confirm, then "Emergency" is selected. Otherwise "Normal" should be selected. For This, I am using jquery:
$(document).ready(function() {
$('#priority').change(function(){
if($(this).val()=='1'){
if(confirm("Are you sure this is emergency?")){
return true;
}
else{
//here some code is needed to select "Normal".
}
}
});
});
Now, How can I do that?
Since you're just returning in the confirmation case, you can shorten your logic down to this:
$(function() {
$('#priority').change(function(){
if($(this).val()=='1' && !confirm("Are you sure this is emergency?")){
$(this).val('3');
}
});
});​
You can give it a try here.
else{
$(this).find("option[value=3]").attr("selected","selected");
//and trigger change after that if you need it
$(this).change();
}
The following code snippet should do what you are after - it selects the priority select element by ID and then sets the selected value to 3.
else
{
$('#priority').val(3);
}

Categories