Javascript Checkbox Ticked on Load Error - javascript

I have a .cshtml page that I'm going to set up with several checkboxes.
The checkboxes should be checked/unchecked depending on the values of several variables passed into the view using the TempData.
I've set up the code as follows:
<script>
#if (TempData["enabled"] == "True") {
var eCheckBox = document.getElementById(eCheck);
eCheckBox.checked = true;
}
</script>
<h2>Update #TempData["fullName"]</h2>
<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck"/>Enabled<br/>
But the line
eCheckBox.checked = true;
produces the error 'identifier expected;checked is a keyword'. Is there something obvious I'm missing? Making a checkbox ticked on load seems like it should be simple to do.
EDIT: I tried to correct the code as follows:
<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck" onload="checkTrue()"/>Enabled<br/>
<script type="text/javascript">
function checkTrue() {
alert("Here!");
if (TempData["enabled"] == "True") {
document.querySelector('[name=enabledCheckbox]').checked = true;
}
}
</script>
It doesn't look as though the code is hitting the function at all, as no alert fires.

You miss to retrieve your HTML element correctly through JS. Just use this:
document.querySelector('[name=enabledCheckbox]').checked = true;

Related

How to back to begin process jQuery

I have a modal form and an input field with checkbox type. I want to create an update form, so I should request data from php and passing to html. So I have two conditions, if parameter = 0 attribute checked="checked", else attribute checked become unchecked. So I use jQuery, this is my code:
<input class="form-check-input" type="checkbox" value="Ya" name="agenda_pimpinan" id="tampilkan_agenda_pimpinan" checked="checked"/>
<script type="text/javascript">
var x = event.tampilkan_agenda_pimpinan;
console.log(x);
if(x != 0) {
$('#tampilkan_agenda_pimpinan').removeAttr("checked");
}
else {
$('#tampilkan_agenda_pimpinan').attr("checked");
}
</script>
Assume I have two data that I want to update, we assume the names data1 and data2. Data1 have parameter = 0 and Data2 have parameter = 1. If I click data1, the modal form will come in. The attribute checked has success become still checked. Next, I click data2, the attribute checked has success become unchecked. But if I back click data1, the attribute checked become unchecked. I don't know how to write code so that the attribute will back to begin.
How to fix it?
$(function () {
var x = event.tampilkan_agenda_pimpinan;
//$('#tampilkan_agenda_pimpinan').attr("checked");
if (x != 0) {
$('#tampilkan_agenda_pimpinan').removeAttr("checked");
} else {
$('#tampilkan_agenda_pimpinan').attr("checked");
}
});

JavaScript if Statement after page been loaded

I have the following if statement:
echo "<a href='searchPage.php?user_query=$crs_sub1&search=search' id='liSpacing'><label id='labelSearch'><input id='checkbox1' type='checkbox' name='checkbox' value='value' checked> $crs_sub1</label></a> <br />";
JavaScript
<Script>
var crs_category1 = document.getElementById("checkbox1").checked;
if (crs_category1 === false){
}else{
document.getElementById("checkbox1").style.visibility = "hidden";
}
</script>
The issue I have is that only checks the input when the page laods. I would want it to be dynamic where after the page as being loaded, once the checkbox is untick, the line goes hidden
The desired effect should occur if the script is inserted directly after the checkbox.
However, it should be noted that the script only checks for the checkboxes value once.
This can be resolved by doing :
<script>
document.getElementById("checkbox1").addEventListener('change', function() {
var crs_category1 = document.getElementById("checkbox1").checked;
if (crs_category1 === false){
} else {
document.getElementById("checkbox1").style.visibility = "hidden";
}
});
</script>
By the way, you can used checked="checked" on a checkbox to make it selected by default, as you wished for in your post. Remember to change the if statement should you do this.
what would be your reference element that you are trying to hide? I mean you can not checked and unchecked if the element is once hidden. so window.onload function should do the work. it has other ways to do it too based on your requirement.

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

JS validation, why this code won´t work?

I can´t get the validation in JS, and don´t understand why it doesn´t work.
The user should get an alert if at least one of the checkboxes isn´t checked.
It doesn´t work, because the form gets submitted ok even if if none checkboxes are checked.
<body>
<script>
function validar()
{
var s1=document.getElementById('s1');
var s2=document.getElementById('s2');
if (s1.value==''||s2.value=='')
{
alert("You must check at least one!");
return false;
}
}
</script>
<form name="calcular" onsubmit="return validar()" method="post">
<input type ="checkbox" name="servicios[]" id="s1" value="sinservicios">Sin servicios<br>
<input type ="checkbox" name="servicios[]" id="s2" value="dosservicios">Dos servicios<br>
...
You may try using the checked property to ensure that at least one of the 2 checkboxes is checked:
<script>
function validar() {
var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');
if (!s1.checked && !s2.checked) {
alert('You must check at least one!');
return false;
}
return true;
}
</script>
Also notice we should return true in case the validation succeeds.
The reason why your code doesn't work is because you have used the value property. That's always gonna return the value attribute of your checkbox (sinservicios or dosservicios) no matter if the user checked or not this checkbox. It will never return an empty string which is what you seem to be testing for in your if condition.

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources