J.S not executing all commands - javascript

In the following code, each "Id" is connected to a checkbox, so when I check it a word is printed and if I uncheck it the word disappears.
function DrawRequest()
{
if(document.getElementById("name").checked == true)
document.getElementById("drawrequest").innerHTML="checked";
else
document.getElementById("drawrequest").innerHTML="";
if(document.getElementById("surname").checked == true)
document.getElementById("drawrequest").innerHTML="checked";
else
document.getElementById("drawrequest").innerHTML="";
if(document.getElementById("age").checked == true)
document.getElementById("drawrequest").innerHTML="checked";
else
document.getElementById("drawrequest").innerHTML="";
}
Or at least that is what should have happened when I tried the code. What really happened is that when I checked the checkbox with id "name" nothing printed. The also happened with the checkbox with id "surname." But the last checkbox with id "age" works fine!
One more question: if the three checkboxes are checked will Ihave three words printed ?
Thanks a lot :)

You always update the innerHTML for each box, whether it's checked or not. And each if or else will overwrite what the previous statements set, making the previous actions irrelevant.
You'll want to either:
set the innerHTML to blank at the beginning of the function, get rid of the elses, and only set the HTML to "checked" if a box is checked (not doing anything if it's unchecked), if you want one "checked" total if any box is checked;
append to the HTML rather than setting it, if you want a "checked" for each box; or
Have a separate element to reflect each box's checkedness.

Related

Click all checkboxes on a webpage with HTML script (quickbooks/Safar)

So I created the following script to select all check boxes on a page
(function(d) {
var input = d.querySelectorAll('input[type="checkbox"]');
var i = input.length;
while (i--) {
input[i].checked = true;
}
})(this.document);
It does work to do that, however when trying it in Quickbooks while it does select all the boxes, the website does not register it as actually being selected (the total cost at the bottom remains the same, its like it superficially checks the boxes, visually only with no actual register). Any help would be great.
EDIT: Maybe simulating a click instead of changing the box values?
The only thing that changes when physically selecting a box is the value posted below changes to true from false
You should do :
input[i].setAttribute("checked", "");
The checked attribute is a boolean attribute, so the standard way to add it to an element is to pass an empty string for value.
https://developer.mozilla.org/fr/docs/Web/API/Element/setAttribute#Exemple

Remove specific text from a paragraph Jquery

In the code below there are check-boxes and every time a check box is checked it add that check-box value (works). But when it is unchecked it should remove that check-box value. But instead it is just adding the value twice. How do I add and remove that value that is unchecked?
Here is the code sample
//Looks for every checkbox
$('#index '+ selected +' #cbFieldSet .icheck').each( function(i, name){
console.log("#"+ $(name).attr("id"));
if($('input[name='+$(name).attr('name')+']').attr('checked', false)){
//checks what checkbox has been check. Gets that checkbox id
$('#index '+ selected +' #cbFieldSet #'+ $(name).attr("id")).click( function(){
// $("#cb-"+playerStart).click(function(){
//console.log(i);
console.log('yes');
//add to popup box paragragh
$('#popupDialog #info').append($(name).val());
});
}else if($('input[name='+$(name).attr('name')+']').attr('checked', true)){
//checks what checkbox has been check. Gets that checkbox id
$('#index '+ selected +' #cbFieldSet #'+ $(name).attr("id")).change( function(){
// $("#cb-"+playerStart).click(function(){
//console.log(i);
console.log('yes');
//add to popup box paragragh
$('#popupDialog #info').remove( ":contains("+ $(name).val() +")" );
});
}
});
This code is not easy to read, partly because you have copy-pasted the same comments in both the "checked" and "unchecked" cases. You've also left out some context-- the indentation is off, and I don't know what selected is.
Anyway-- in addition to what user3785863 has said above, the form of .attr() you're using sets attribute values, when you want to read the existing value.
In other words, $('input(...)').attr('checked', false) does not test whether the checkbox is checked; it sets its value to boolean false, and then returns the checkbox itself, which means your first if statement will always run, and the second one never will.
So, I think what you actually mean is if ($(...).attr("checked") == "false").
(I think you also have true and false the wrong way round, plus some other issues, but this might get you unstuck...)
Depending on which version of jquery is used, you might want .prop() rather than .attr().
Only versions pre-1.6 have attr("checked",true/false) i.e. as boolean.
.prop( "checked" ) should do the trick

Hiding Selected item with Jquery

I have this code
$("#tag_price").on('change', function(event) {
if ($(this).val() == -2)
$('<input type="text" class="ipt" id="customprice" name="customPrice" />').insertAfter(this),
$('<p id="customprice" class="semi_margin_top">Introduce el precio exacto</p>').insertAfter(this);
else if ($(this).val() !== -2)
$('#customprice').hide;
});
The first part is working, when the input has value -2, the second input is shown. But I want it to dissappear when another value is selected, because if not the second input will remain forever.
I want the second input ONLY to show when value -2 is selected, and dissappear when another value is selected. I thought I could achieve that with Jquery and hide, but I't wont work.
Thank you!
The corollary to hide() you're looking for is show(). There are a few other issues with your code that you'll need to take care of as well.
First, you're missing { } around your if statement, so your else if should be throwing an error as the $('<p...') line is outside of the if.
Secondly, there's no need for else if as there isn't a 3rd option. The value is either "-2" or it isn't.
Right now, you're appending a new element every time that someone selects the "-2" item, which is not the right way to do it. Check to see if those elements are already in the DOM, and only add them if they aren't there. If they are, then call show().
if ($(this).val() === -2) {
$('#customprice').show();
}

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

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.

Changing checkbox's parent element css if checked or unchecked

Basically I have a checkbox inside a td element and I want it to have one background color when the checkbox is checked and another background color when the checkbox is unchecked. So in other words I want it to highlight whether it's checked or not.
I tried to use the same solution as in here: Jquery toggle event is messing with checkbox value
But for some reason I can't get it working.
$(document).ready(function(){
$("input:checkbox").change(function() {
if($(this).attr("checked") === "true") {
// CHECKED, TO WHITE
$(this).parent().css({"background" : "#ffffff", "-moz-border-radius" : "5px"});
return;
}
//NOT CHECKED, TO GREEN
$(this).parent().css({"background" : "#b4e3ac", "-moz-border-radius" : "5px"});
});
});
It does add the green background color but doesn't remove it. And if I leave a checkbox checked, refresh, the td is back to white and once clicking on the checkbox again, unchecking it, it changes the td's background to green.
I'm still new to this, have no idea what could be wrong here, been trying to figure it out for hours now. Such a simple thing but just can't get it working.
There is a better way to see if the checkbox has been checked:
$(this).is(':checked')
It is a bit more robust.
Change
if($(this).attr("checked") === "true")
to
if($(this).attr("checked") === true)
Snce you are comparing using strict equal the two data types must be the same.
typeof ( $(this).attr ( "checked" ) )
will let you know that it is of boolean type and you are comparing it to a string.
For more info see Comparison Operators
if ($(this).attr("checked") === "true")
attr does not read HTML attributes. It's deceptive that way. If it did read attributes, the string value for checked would be 'checked' and not 'true'. But it doesn't do that.
What it actually does is read JavaScript object properties, only using attribute names instead of property names in the few places they differ. The checked property gives you a boolean value so there's no need to compare it to anything, you can just say:
if ($(this).attr('checked'))
or, even simpler, the totally equivalent:
if (this.checked)
best one is
if($("this").is(':checked'))
{
$(this).parent().css({"background" : "#ffffff", "-moz-border-radius" : "5px"})
}
Check out this article on the difference between =, == and === in javascript. Or this on equality operators in js.
Try changing this:
$(this).attr("checked") === "true"
to this:
!!$(this).attr("checked") === true
This will convert any non-boolean to a boolean and allow your type safe comparison to work even if the string "true" is returned (if the string false is returned it will evaluate to true though....)

Categories

Resources