Linking checkbox's checked state to a value of a textbox - javascript

Would like to know how to link a checkbox's checked state to a value on a textfield returned from an sql query. The textbox value is updated after a user selects a value from a select/menu on the form. The value of the select menu option is used as a filter in the query, which is working fine.
if ($('#textbox').val("TRUE")
{ $('#mycheckbox').prop('checked',true);}
else
{
$('#mycheckbox').prop('checked',false);
}
The problem is that the if statement works for the previous value the user selected. So its always one click behind even though the textbox value is current. Although the value of the textbox is current on the form, when I make an alert box displaying the textbox's value, it too is behind. So the if statement is ok, its just its using the textbox's previous value and not the current one. Any way to make this current?

First, you have syntax error in your code, assuming that is a typo.
What you are doing by$('#textbox').val("TRUE") is setting the value of textbox to TRUE.
So whenever your code block will execute you will end-up with checked check box, and textbox with TRUE value.
If your goal is to update the checkbox as per the value of text box. you can put the following one liner code instead of your four line, when you are actually setting/updating the value of text box.
$('#mycheckbox').prop('checked',$('#textbox').val() == "TRUE")
Update
As you mentioned you are setting the new value after a ajax call and didn't included your code sample, I'm guessing, your code is something like:
$.ajax({
url: "your/url"
}).done(function(data) {
$('#textbox').val(data)
});
If so, update your code to
$.ajax({
url: "your/url"
}).done(function(data) {
$('#textbox').val(data);
$('#mycheckbox').prop('checked',$('#textbox').val() == "TRUE");
});
The response is based on guess.

Your if statment is not testing the value of #textbox it is actually setting a value.
Try changing your if statement to read:
if ($('#textbox').val() == "TRUE")
Here's another SO post that might help.

Related

javascript jquery dropdown listbox - How to set option text at specific index (not selected!)

My question is, using javascript / jquery, "How do you change the value of a dropdown option at a specific index that is NOT the selected index?"
I have a dropdown list of values. User can select an option. I have a method which enables the user to change the value at that selected option. The value gets changed and all is well.
Here is my issue: If the user decides to cancel, or changes to a different value in the list without saving the changes to the database, I want to undo the value change.
I have the index of the changed option.
I have the old value of the changed option.
I have the new value of the changed option.
If the user has selected a different option, I don't want to change the index of the newly selected option. I just want to reset the value of the option the user changed.
I've tried a .each method:
var changedTitle = $('#ddTitle').text();
$("#ddTitle option").each(function() {
if($(this).text() == changedTitle) {
$(this).text(savedTitle);
}
});
I like the idea of looping through each one but I never see execution loop through a second time and the browser never comes back.
I've tried a .filter method:
var changedTitle = $('#ddTitle').text();
$("#ddTitle option").filter(function(index) { return $(this).text() === changedTitle; }).attr('selected', 'selected');
$("#ddTitle option").filter(function() {
return $(this).text() === changedTitle;
}).prop('selected', true); // changes the selected option
I got the above filter code to work but it sets the selected option.
$("#ddTitle option").filter(function() {
return $(this).text() === changedTitle;
}).prop('text', savedTitle); // execution never returns
I tried using the text property on the option but jquery gets very busy and execution never returns.
I've tried finding by the text value, which is silly because I know the index:
$("#ddTitle option[value='" + theText + "']").attr('selected', 'selected');
If these get an option it is the first option (0) or the browser hangs.
Is there a way to change the text value at a specified index programmatically in javascript or using jquery? Nothing I've tried works.
To change the value of the 5th option, do:
$('#yourselect').children('option:eq(4)').html('your text');

Getting value from mdl radio button

In the following code why doesn't the radio report the correct value when checked via its variable name?
var $myRadio = $('input[type=radio][name=options]:checked');
$('#button').click(() => {
// this works
console.log($('input[type=radio][name=options]:checked').val());
// this doesn't :(
console.log($myRadio.val());
});
https://jsfiddle.net/charsi/p4beztwx/13/
I am using mdl radio buttons so that could be causing it. I have also tried getting the value with $myRadio[0].MaterialRadio.value but that doesn't work either.
EDIT: This was a poorly worded question and didn't really have anythng to do with mdl. What I really wanted was the ability to set the DOM variable for my radio button somewhere else without having to select it by name again to check the value.
The reason for getting incorrect values when checked via its variable name is because you are setting $myRadio before the click event. $myRadio is set on document ready (before click event) and it gets the value of the checked radio option which at this moment is always 1.
Moving $myRadio inside a click handler should work. Why? Because now it gets the value of the radio (checked) as soon as the click function is called which is actually what you need.
$('#button').click(() => {
var $myRadio = $('[id^="option"]:checked');
// neither of these work
alert($('input[type=radio][name=options]:checked').val());
alert($myRadio.val());
});
fiddle here
For anyone else running into the same issue. Not wanting to call the radio button name when checking for its value, you can use filter -
var $myRadio = $('input[type=radio][name=options]');
$('#button').click(() => {
console.log($myRadio.filter(':checked').val());
}

Change disabled select(dropdownlist) based on another select(dropdownlist) value

Basically what I'm trying to do is self-explanatory in the title. Here's a snippet of code which enables the dropdown/select so it can be changed via client, but it will not disable after change:
function setLocVals(passedVal) {
$('#DropDownList1').removeAttr("disabled");
$('#DropDownList1').val(passedVal);
$('#DropDownList1'').attr("disabled", "disabled");
}
Is this even possible? Or am I looking at this completely the wrong way?
I could change to a textbox, but this is a dropdown containing US states. If there's a record for the user then the selection is restricted for the user, if no record exists, then they can select.
Just put a condition when you have to disable. See this fiddle
Use this approach.
First set the value in option.
Then retrieve the current value of the option and check if it is set to the one than you have passed then put the condition to disable else not
function setLocVals(passedVal) {
$('#DropDownList1').val(passedVal);
var value = $('#DropDownList1').val();
if(value == passedVal){
$('#DropDownList1').attr("disabled", "disabled");
}
}

How to find dropdown's selected option's index/value using javascript, before the selection change

I am not sure if the title of my question is meaningful enough, so here is my problem :
I have a dropdown dynamically generated from server side as below:
sb.append("<SELECT NAME='selectedQAStatuses' id='selectedReleaseQAStatuses' onchange='javascript:changeReleaseQAStatus(\""+releaseId+"\",\""+depEventSeq+"\",this);' >");
sb.append("<OPTION>Please select a QA status...</OPTION>");
for (String status : statusArray) {
if(status.equals(releaseStatus))
sb.append("<OPTION VALUE='"+status+"' selected>"+status+"</OPTION>");
else
sb.append("<OPTION VALUE='"+status+"'>"+status+"</OPTION>");
}
Now javascript : changeReleaseQAStatus() is getting called. In this javascript method I am calling a confirm() to see if user is sure or not. If user selects "OK" in the confirm popup then from the "IF" block i make a Ajax call etc., but if user selects "Cancel" in the confirm popup, then from the "ELSE" block I return from the JS method.
However, in "Cancel" scenario i see that although the user seems to have "Cancelled" his selection, still on the browser screen the dropdown seems to show the new option as "selected".
Therefore I think, in Javascript's "ELSE" block i should write something which should revert the selection to the original selection. How am I supposed to 'remember' what was the original value of the dropdown when the page had rendered on the browser, so that I can user this initial value in my 'ELSE' block to restore my dropdown.
My Javascript to handle 'OK' and 'CANCEL':
function changeReleaseQAStatus(releaseSeq, depEventSeq, element1){
var selectedIndex = element1.selectedIndex;
var selectedStatus = element1.options[selectedIndex].value;
if (confirm("Do you want to change Release QA status to \"" + selectedStatus + "\" ?")){
url = contextPath + "/changeQAStatusOfRelease.action?selectedStatus="+selectedStatus+"&releaseSeq="+releaseSeq+"&depEventSeq="+depEventSeq;
ajaxUpdate({url:url,
elementId:'compReleasesDtlsDiv',
});
}else{
/// No Code needed to execute here...
}
}
by using javascript you can use something like this
var arr = document.getElementsById('select_id');
alert(arr[0].options[arr[0].selectedIndex].value);

overriding data-confirm values

I want to change the value of data-confirm attribute on a button (submit) based on user's choices on a form. I put the following on the change function of a dropdown list:
...
if($("#"+select_name).val() == "abc")
{
$(".variable_button").attr("data-confirm","abc is good choice!");
} else
{
$(".variable_button").attr("data-confirm","abc would have been great but this is fine too...");
}
...
The problem I am facing is that apparently data-confirm cannot be changed once it is assigned a non-empty string. I have it set to "" in the server code. And, it changes to one of the two messages shown above when the user first makes a selection on the dropdownlist. But if the user changes the selection one more time, the data-confirm message does not change. Is this per design or am I missing something?
Don't use .attr(), use .data():
var newData = ($("#"+select_name).val() == "abc")
? "abc is good choice!"
: "abc would have been great but this is fine too...";
$(".variable_button").data("confirm", newData);
jQuery does allow you to update a data- attribute with the .attr() method, so something else is breaking.
Here's a working example (JSFiddle):
var counter = 1;
$('#click').click(function() {
button = $('#click');
console.log(button.attr('data-confirm'));
button.attr('data-confirm', 'this is test ' + counter);
console.log(button.attr('data-confirm'));
counter++;
});
Can you try to repo the issue in a JSFiddle?
On rereading your question, it sounds like an event handler isn't firing the second time the user changes the selection. See if you can set a breakpoint in your event handler to see if it even gets hit.

Categories

Resources