In my models.py I have
urgency = models.BooleanField(blank=True, default=False, verbose_name="Hitno otklanjanje")
And I wish to run a javascript function to change a text field depending on 'True' or 'False' on that Boolean field. Problem is, I can't get the value. When I use document.getElementById('id_urgency').value; I always get 'on', no matter of clickbox check. Why is that? I guess I'm reading the value wrong? Or?
<script type="text/javascript">
function makeReadOnly()
{
var a = document.getElementById('id_urgency').value;
console.log(a);
if (document.getElementById('id_urgency').value == 'True'){
document.getElementById('id_date_days').readOnly = true;
}else if (document.getElementById('id_urgency').value == 'False'){
document.getElementById('id_date_days').readOnly = false;
}
}
document.getElementById('id_urgency').addEventListener('change', makeReadOnly);
This is a part of django form. If I go to 'inspect' on that page, that Checkbox doesn't even have value, why is that?
input type="checkbox" name="urgency" class="checkboxinput form-check-input" id="id_urgency"
By using .value, you get the value attached to that checkbox, not whether the checkbox is checked or not.
You can check if a checkbox is checked with:
var a = document.getElementById('id_urgency').checked;
or as specified by javascripttutorial.net:
To check if the accept checkbox is checked, you use the following
code:
const cb = document.getElementById('accept');
console.log(cb.checked);
(…)
If you get the value attribute of a checkbox, you always get the 'on' string whether the checkbox is checked or not. For example:
const cb = document.getElementById('accept');
console.log(cb.value); // on
Related
I've had a problem where I wrote a checked() function for the onchange of a checkbox:
<input
type="checkbox"
id = "checked"
onchange="checked()"
/>
Here's my javascript:
const check = document.getElementById("checkbox")
const yes = document.getElementsByClassName("yes")
function checked() {
if (check.checked) {
yes.innerHTML = "Yes"
} else {
yes.innerHTML = "No"
}
}
Basically I want the span with the class of yes to change output depending on if the checkbox is checked or not (Says Yes or No)
However, when I inspect, it says "TypeError: checked is not a function
at HTMLInputElement.onchange" even though my javascript is perfectly linked to my HTML (I checked this with an alert).
How can I solve this?
You're getting checkbox by id checkbox, but in your input field, you put id="checked" which is incorrect, so you need to correct your id from checked to checkbox.
<input
type="checkbox"
id = "checkbox"
onchange="checked()"
/>
You also need to change your function name from checked to another name (like checkData which is not similar with native values/functions) and then wrap your document.getElementById into your function
You should not use getElementsByClassName too, because it returns a list of elements and innerHTML does not work for those, so you need to select a particular element with getElementById
function checkData() {
const check = document.getElementById("checkbox")
const yes = document.getElementById("yes") //need to use `getElementById` instead of `getElementsByClassName`
//if `yes` element is not there, we don't need to set `innerHTML`
if(!yes) {
return
}
if (check.checked) {
yes.innerHTML = "Yes"
} else {
yes.innerHTML = "No"
}
}
Remember to implement your yes element like this
<p id="yes"></p> //tag name is your choice
Technically, checked is the name of the value attribute on that input and it's not a function, so you cannot use it as a function name.
By the way, thank #Teemu for the suggestion!
const check = document.getElementById("checkbox")
There is no such ID in your code named "checkbox". I think you want:
const check = document.getElementById("checked")
Try giving your IDs, function names and input-types unique names so you won't get them mixed up with each other.
I am learning AngularJS. I am trying to make a custom directive that checks if email already exists. I get my emails from array that has like 9 users and I can successfully get them using Factory. My problem with my custom directive is that no matter what input I enter the button will be disabled. The idea of the directive is when I lose focus it will check if the email exist or it doesn't if it does it will disable the button if it doesn't then the button will be enabled.
.directive("registerUser",function(){
return {
link:function($scope, element) {
element.bind('blur',function () {
var emailInput = element.val();
var flag = "false";
$scope.registeredUsers.forEach(element => {
if(emailInput === element.email){
flag = "true";
console.log(emailInput);
console.log(flag);
return;
}
});
$scope.invalidemail = flag;
});}
}
})
That is my directive as you can see I tried using flags it didn't work I tried changing the flag to booleans still not working I will also show my HTML. I am not sure if var emailInput = email.val() making problems to me because I am not using ng-model.
<form action="">
<input type="text" name="emailField" ng-model="emailInput" register-user>
<input type="button" name="" value="check" ng-disabled= invalidemail>
</form>
That is my HTML. Note I am not checking if email is valid in this task. I am just checking if the email already exist in my array or not.
The value of flag is being set to a string of "true" or "false" instead of boolean values of true or false.
// not "false"
var flag = false;
// subsequently set it to true not "true"
Your form template has a space between ng-disabled and the bound value.
<input type="button" name="emailButton" value="check" ng-disabled="invalidemail" />
You can also write this more concisely using Array.some() to see if the array contains your value.
const emailInput = element.val();
$scope.invalidemail = !$scope.registeredUsers.some(element => emailInput === element.email);
I'm trying to leverage some form validation to do something it really wasn't designed to do. I have a table in my form and each row has a checkbox. I want to ensure that at least one of a specific type of checkbox is selected, if not I want to show a validation error. I am doing something similar with a text box with logic that looks like this:
function ValidateName() {
var $nameTextbox = $("#Name");
var $originalName = $("#OriginalName");
var nameText = $nameTextbox.val().toLowerCase();
var originalNameText = $originalName.val().toLowerCase();
//check to see if original name and group name match
if (nameText != originalNameText) {
//This isn't the same name we started with
if (uniqueNames.indexOf(nameText) > -1) {
//name isn't unique, throw validation error
var currentForm = $nameTextbox.closest("form");
//trigger validation
var errorArray = {};
errorArray["Name"] = 'Name must be unique';
currentForm.validate().showErrors(errorArray);
}
}
}
I've written something similar for the table and it works as long as I point the errorArray's index to the id of an input. However, I want to display the error somewhere more generic like the validation summary at the top of the form. How do I set up the error array to show on the form or the validation summary instead of a specific input? Is that even possible?
One way you could do this is you set a hidden input that is false when none are check and true if 1 or more are checked. You then listen to all the checkboxes by giving them all a class. I have an example shown below
http://jsfiddle.net/95acw2m9/
Html
<input type="hidden" id="IsCheckValue" name="IsCheckedValue" value="false"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
Jquery
$(document).ready(function(){
$(".someCheckbox").change(function(){
if($(".someCheckbox:checked ").length > 0){
$("#IsCheckValue").val("True")
}else{
$("#IsCheckValue").val("False")
}
})
})
Then pass that bool value in your model. In your controller method you can check the value of the bool. If the bool is false set the model to false like this
ModelState.AddModelError("Checkbox", "Must select one checkbox");
You can use the #Html.ValidationSummary() to display the error in your view.
I want to save a checkbox with localstorage. So that when i have checked the box and I close the browser and i re-open it, it will still be checked. right now if i click on the checkbox and i press the save button it doesn't save the checkbox.
how can i achieve this?
this is my code:
<script>
function save(){
var checkbox = document.getElementById('checkbox1zaal1');
if(document.getElementById('checkbox1zaal1').checked) {
localStorage.setItem('checkbox1zaal1', true);
}
}
function load(){
var checked = localStorage.getItem('checkbox1zaal1');
if (checked == true) {
document.getElementById("checkbox1zaal1").setAttribute('checked','checked');
}
}
function wis(){
location.reload();
localStorage.clear()
}
</script>
<body onload="load()">
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>
<input type="checkbox" id="checkbox1zaal1">1e film van de dag</input>
</body>
thanks for any advice!
1). Because boolean true is not equal to string "true". So comparison checked == true is always false, and checkbox never gets checked.
Instead try this:
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
if (checked == true) {
document.getElementById("checkbox1zaal1").checked = true;
}
And remember whatever you store in localStorage is always a string, and only a string. That's why when you save something more complex then primitive value (for example some object) make sure to use JSON.stringify on it first.
When you retrieve the value from localStorage you should convert it back to it's corresponding javascript type.
In general load function can also be improved:
function load(){
var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
document.getElementById("checkbox1zaal1").checked = checked;
}
2). Another problem will come up once you try to uncheck checkbox. You are not handling it currently, so change save function to this one:
function save(){
var checkbox = document.getElementById('checkbox1zaal1');
localStorage.setItem('checkbox1zaal1', checkbox.checked);
}
Demo: http://jsfiddle.net/Lwxoeyyp/1/
The problem is that you are storing value as "true" in localStorage which is a string format, Now at time of loading the page value is retrieved as string and you are comparing that String "true" with boolean true. This will return false. One small change as
if (checked == "true")
now this should work.
You can also retrieve the status of your checkbox this way:
var selCheck = document.getElementById("checkOne");
selCheck.checked = (localStorage.getItem("34_chkOne")=="true");
Obviously,
"checkOne" is the id of the checkbox.
"34_chkOne" is the name of the local storage variable.
To store the value, you simply use
var selCheck = document.getElementById("checkOne");
localStorage.setItem("34_chkOne", selCheck.checked);
and, as said above, a variable of type string will be stored.
am using this jquery code and is working with me better
$(function() {
var sound_t_s_data = localStorage.getItem("sound_t_s");
if (sound_t_s_data == "yes") {
$("#sound_t").prop('checked', true);
}
else if(sound_t_s_data == "no"){
$("#sound_t").prop('checked', false);
}
});
$("#sound_t").click(function() {
if ($(this).is(":checked")) {
localStorage.setItem("sound_t_s", "yes");
} else {
localStorage.setItem("sound_t_s", "no");
}
});
And if you want to us it in function use like this
//Play Audio
const s_a = new Audio("audio/s_a.mp3");
$( "#s_r" ).click(function() {
if ($('#sound_t').is(':checked')) {
s_a.play()
}
});
I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property. THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />
and the javascript function is
function test_check(params) {
if(conditions){
return true;
}
else
return false;
}
But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
<input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>
4 radio buttons make a group. such N radio groups have html class names in this way : button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/
Assuming you are using jQuery, use the change event: http://api.jquery.com/change/
The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)
$.each(args, function(index, value) {
$("INPUT[type=radio]").eq(index).attr("checked", value)
});
Here's a fiddle to show what I mean more clearly
check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />
js:
$(function() {
var radios = $("input[type='radio']");
$.each(radios, function(index, value){
var args = value.attributes[1].nodeValue;
test_check(args, value);
})
});
function test_check(params, value){
if(params == "aa"){
$(value).attr("checked",true);
}else
$(value).attr("checked",false);
}
try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>
$('input:radio').each(function() {
if ($(this).attr('groupname') == 'gr1') {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
Your question really boils down to:
How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)
The key insights are:
you can't store a function inside a parameter and expect it to automatically evaluate on load
you can store the data about an object inside data- properties
you can set the value of objects on page load in jQuery using the $(document).ready() event
.
<script type="text/javascript">
$(document).ready( function() { // this code runs when the page is first loaded
var radios = $("input[type='radio']"); // find all of your radio buttons
$.each(radios, function(){
var radio = $(this);
var param = radio.attr('data-param'); // retrieve the param from the object
radio.attr('checked', test_check(param) ); // set the value of the radio button
})
});
function test_check(params) {
if(conditions){
return 'checked';
}
else
return '';
}
</script>
You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">
<script>
// Do test_check on param for each input
$('input:radio').each(function()
{
var radio = $(this);
var param = radio.attr('needs_check');
var condition = test_check(param);
radio.attr('checked', condition);
});
function test_check(param)
{
return true or false based on param
}
</script>
I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />
Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />