Checkbox validated as "on" when form is submitted unchecked - javascript

I have a form here: http://www.problemio.com/test.php when you click on the "Click To Test Signup"
If you just submit the form without filling it out, the JS validation realizes that all the fields are empty, except for the checkbox at the bottom. It says that the checkbox is on even if it is unchecked.
Any idea why that happens? And what is the right way to validate the checkbox there?
var terms_and_conditions = $("#terms_and_conditions").val();
and this line outputs it as :on" alert ("Data string " + dataString);
Thanks!!

Use this instead to get the right value.
$("#terms_and_conditions").is(':checked')

you have to test like this (using the :checked-selector):
var terms_and_conditions = $("#terms_and_conditions:checked").val();
or, better, use .prop():
var terms_and_conditions = $("#terms_and_conditions").prop('checked');
this is because the value on a checkbox is always set - the only thing that changes is the checked-state so this is what you really have to test.

Try -
var terms_and_conditions = $("#terms_and_conditions").prop("checked");
that should return a boolean depending on whether the checkbox is checked or not.

you can try this:
$("#terms_and_conditions:checked").val();
you either get the val() or undefined.

Change this line from this:
var terms_and_conditions = $("#terms_and_conditions").val();
to this:
var terms_and_conditions = $("#terms_and_conditions").is(":checked");

Related

Set Text Field By Radio Choice

This is my first real attempt to write a JS function. I want to set the value of a text field depending on the selction of a pair of radio buttons.
<script type='text/javascript'>
function setInputValue(){
if(document.getElementById('choice_8_0').checked) {
document.getElementById('input_6_18').value = '1';
}else if(document.getElementById('choice_8_1').checked) {
document.getElementById('input_6_18').value = '0';
}}
</script>
Can anyone help me with where I went wrong? I am not even sure how to name the function really.
You could use:
document.getElementById('elementId').checked = true;
or
document.getElementById('elementId').checked = false;
To select a radiobutton, you can use the checked property of the radiobutton:
document.getElementById('input_6_18').checked = true/false;
EDIT: seems like you want to set the text of an input type text?
Than your code is correct, the property is value. So what is the problem?

Check if a checkbox is checked in JS

I am new to js and jquery. Currently, I have a form at form.php which contains a checkbox. When the user clicks submit, the form variables are sent to a form.js file where each value is checked to be null or not.
The form.js file works perfectly, however, for the checkbox nothing seems to happen. I have a feeling this is due to the way I have declared the variable.
The following is the code for the js file:
var email = $('#email').val();
var website = $('#website').val();
var CHECKBOX = $('CHECKBOX').val();
...
...
if (CHECKBOX.checked == FALSE){
var error = true;
$('#notchecked_error').fadeIn(500);
}else{
$('#notchecked_error').fadeOut(500);
}
Try using:
if ( $('#CHECKBOX').prop("checked") )
or:
if ( $('#CHECKBOX').is(":checked") )
Also, be sure your selector for the checkbox is correct.
I see two problems in your code. The first one is that the selector in your CHECKBOX assignation is faulty. It should be
var CHECKBOX = $('#CHECKBOX').val();
or
var CHECKBOX = $('input[type=checkbox]').val();
the second problem is that you are reading CHECKBOX.checked from the val() function, you need to read it from the checkbox itself.
if(CHECKBOX.checked)
$('input[type=checkbox]:checked') // If you have multiple checkboxes you can use this and loop through them to get additional info
$('#checkboxID:checked').length // To get one specific checkbox
`$('CHECKBOX').val();`
Will try to find an element with a tagname of CHECKBOX and return it's value. Presumably you want to reference the checkbox with an ID of CHECKBOX:
var CHECKBOX = $('#CHECKBOX');
To see if it's checked:
if (!CHECKBOX[0].checked) {
// CHECKBOX is not checked
}
You really should learn basic javascript before using jQuery. Usually validation is initiated from a form submit, which can give you are reference to the form. You can then reference all of the form elements as properties of the form, you don't need to create all of those jQuery objects. e.g. if you form is something like:
<form ... onsubmit="validate(this)"... >
<input type="checkbox" name="checkbox">
</form>
Then in your validate function:
function validate(form) {
if (!form.checkbox.checked) {
// the checkbox isn't checked
}
}
You can attach the listener dynamically if you wish.

How to update 2 textboxes with javascript?

How can I update a multiple textboxes value with Javascript, when user change the value of textboxes,
and I have a value already on those textboxes?
Am I doing in the right track on the code below?
<input type="text" id="amount_textbox" onChange="UpdateValue()" value="100">
<input type="text" id="amount_textbox" onChange="UpdateValue()" value="200">
function UpdateValue()
{
//alert ("you have changed the textbox...");
var x = document.getElementById('amount_textbox').value;
document.getElementById("amount_textbox").setAttribute("value", x);
document.getElementById('amount_textbox').value = x;
}
That function is working only for the first textbox, the second one can not update, how can I make other textbox work?
in jquery
$("#text").val("my new value");
in javascript
document.getElementById("text").setAttribute("value", "my new value");
document.getElementById('text').value = 'Blahblah';
First of all, I'm not sure why you'd want to set the value of the textarea(?) to itself - doesn't quite make sense, but here's the code nevertheless.
function checkTotal()
{
var tbox = document.getElementById('ammount_textbox');
var val = tbox.innerHTML;
tbox.innerHTML = val;
}
Your event handler is onClick, but it seems like you want to prevent changes? A click is not a change to the content of a form text box. Perhaps you want onChange?
change your onClick to onKeyup. With textareas, I have been able to access the value using just the value. Since the content is between opening and closing tags, you might be able to use the javascript innerHTML property ("That works with the button tag instead of value"). Good Luck!
function UpdateValue()
{
alert ("you have changed the textbox...");
var x = document.getElementById('amount_textbox').value;
document.getElementById("amount_textbox").setAttribute("value", x);
document.getElementById('amount_textbox').value = x;
}

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.

Changing a checkbox's state programmatically in dashcode

Okay, so I'm trying to change a checkbox's state programmatically in dashcode. I've tried:
var checkbox = document.getElementById("checkbox");
// I have tried all the following methods.
checkbox.checked = false;
checkbox.selected = false;
checkbox.value = false;
Dashboard Widgets just run on WebKit technologies, so code valid for Safari should also be valid in Dashcode. Either of the following should work:
checkbox.checked = true;
checkbox.setAttribute("checked", "true");
The fact that they are not working indicates there is a problem elsewhere in your code. I would check the line
var checkbox = document.getElementById("checkbox");
Correctly assigns an element to the checkbox variable. Also, check the id of your "checkbox" element is valid and correct (not a duplicate, doesn't have a typo, etc).
This question is one month old as I write this answer. It was probably already solved, but in any case I would like to add that if you are using Dashcode, the Checkbox part is a div which contains one label and one input, this one being the "real" checkbox.
If you inspect the html as it is loaded in Safari you will notice that "checkbox" is the type of the element.
Therefore the proper way to change the state of the checkbox would be, assuming "input" is its id (it could have a default number attached though):
document.getElementById("input").checked="true";
or whichever method you want to use.
The main point here is that you were trying to change the state of another div.
Hope it helps!
checkbox.setAttribute("checked", "checked"); // set
checkBox.removeAttribute("checked"); // remove
This question has been around a while. Regardless, the following works for us:
checkbox.childNodes[1].checked = true;
checkBox.childNodes[1].checked = false;
As pointed out in a previous answer, the way Dashcode creates these controls you need to get past the div wrapper, which has the actual ID (checkbox in this example) and set the property for the input, which is child node 1.
Looking for the actual 'id' of the input would be problematic as you have no control over what id's are assigned to the node. For example if you have two checkboxes then the first one would have 'input' as the id for child node 1 and the second one 'input1', unless, of source you have used 'input' or 'input1' as an id somewhere in your design already!
There might be another method but I have not found it yet.
I don't know which browser you used, but when I tested on FF 3.6, it works.
just put like this:
checkbox.checked = false;
while:
checkbox = document.getElementById('blablabla');
or write like that
document.getElementById('idhere').checked = false;
Maybe:
checkbox.checked = "checked";
Then:
checkbox.checked = "unchecked";
cell = row.insertCell(-1);
sel = document.createElement('input');
sel.setAttribute("type", "checkbox")
sel.setAttribute("name", "myCheckBox")
cell.appendChild(sel);
cell.getElementsByTagName('input')[0].checked = true;
I create a table, row then cell and create a checkbox within it.
I can the grab hold of the first input object and set the checked status to true.
var checkbox = document.getElementById("checkbox");
there is a problem with this line, it should be
var checkbox = document.getElementById('#checkbox");

Categories

Resources