JavaScript if Statement after page been loaded - javascript

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.

Related

How to disable anPHP disable and clear textbox when checkbox is unchecked. Check/uncheck checkbox depending on database

I want to disable and clear a textbox if a checkbox is uncheck and enable it when checked. At the same time, the checkbox should be dependent on the value on the database.
If deductstatus == 1, checkbox should be checked when loaded
If deductstatus == 2, checkbox should be unchecked when loaded
The code below is not working. Any help?
$(".dedstat").click(function() {
if ($(".dedstat").is(":checked")) {
$(".deductto").removeAttr("disabled")
} else {
$(".deductto").attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
deductto.value = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat" value="<?php if ($dedstat == 1) echo 'checked'; ?>">
<input type="text" name="deductto" id="deductto" value="<?php echo $deductto;?>">
Checked is not a value, it is an attribute, it should be:
<input type="checkbox" name="dedstat" id="dedstat" value="" <?php if ($dedstat == 1) echo 'checked'; ?>>
When manipulating boolean attributes such as checked, disabled, multiple, you should be using .prop() instead of .attr() or .removeAttr(). Some other suggested improvements:
Use this.checked instead of $(".dedstat").is(":checked"), so that it is context specific
Use the ID selector instead of class
You can chain your jQuery methods, so you can both disable the input and empty its value at the same time
Listen to the change event instead of click for <input> elements
$("#dedstat").change(function() {
if (this.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
If you want the state of the input to be evaluated on pageload, you will also have to perform the same logic without binding it to the onChange event. The best way is to create a function that is called by both the onChange event and DOMready/window.load event. In the example below, the method we create will accept a DOM node as an argument, so that it is contextually aware of which checkbox element you are referring to:
// Method to conditionally enable/disable input
var updateTextInput = function(el) {
if (el.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
}
// Call method when change event is fired from checkbox
$("#dedstat").change(function() {
updateTextInput(this);
});
// Call method on DOMready, pass DOM node (not the jQuery object)
updateTextInput($('#dedstat')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
And with regards to your PHP, you can simply use tenary operators to conditionally write the checked prop to your input element, i.e.:
<input type="checkbox" name="dedstat" id="dedstat" <?php echo $dedstat == 1 ? 'checked' : ''; ?>>
value attribute can not be used to keep it checked or unchecked based on database value. And bind checked or unchecked attribute separately.
So change that tag like this:
<input type="checkbox" name="dedstat" id="dedstat" onclick="isChecked()" value="1" <?php echo (isset($dedstat) && $dedstat == 1)? "checked" : "" ; ?>
More on this,
If you want to store 1 and 2 values to save checked and unchecked condition of the checkbox respectively, then what you should do is, if the checkbox is checked, you will get its value in php $_POST but if it was not checked, you will not get it in $_POST. So in that case, you should store its default value 2 into the DB column. So then only you can get 2 when you fetch its value next time from DB.
Just a little suggestion :
Is your JS at the bottom of the page ?
Plus I just noticed something :
$(".dedstat") <= you're calling a class with the dot. Your imputs have ID's.
$("#dedstat").click(function () {
if ($("#dedstat").is(":checked")) {
$("#deductto")
.removeAttr("disabled")
}
else {
$("#deductto")
.attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
.deductto.value = "";
}
});
It should work a little better.

ASP.NET MVC 4 Having trouble selecting the correct input element using js/jquery

I'm working with a form that I've built using HTML helpers, like so:
#using (Html.BeginForm("CreateNewRoom", "Admin", FormMethod.Post, new { #enctype = "multipart/form-data", #class = "form-vertical", style = "margin-top:-30px" }))
{
<fieldset>
<legend>Create a new Room</legend>
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Room name:</label>
<div>
#Html.TextBoxFor(x => x.name, new { #id = "room", #class = "form-control-static", #style = "margin-bottom:5px;", #autofocus = "true" })
</div>
</div>
...
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Display:</label>
<div>
#Html.RadioButtonFor(x => x.display, "True") Yes&nbsp
#Html.RadioButtonFor(x => x.display, "False") No&nbsp
</div>
...
Just in case it helps, Chrome DevTools informs me that this is the HTML being displayed by my radio button helper:
<input id="display" name="display" type="radio" value="True">
" Yes "
<input checked="checked" id="display" name="display" type="radio" value="False">
" No "
I have a Javascript file which dynamically plays with the elements on the page. I would like for js to add a class to an element on the page, to simply change its opacity to 0.5, if it finds that the "No" radio button is selected.
if ($('input[name="display"]').val() === "False") {
if (($('#selectedRoomName')) && ($('#selectedRoomArrow')))
$('#selectedRoomName').addClass('obscured');
$('#selectedRoomArrow').addClass('obscured');
} else {
//sad
}
I've used this block in $(document).ready and in $(input[name="display"]).change, to make js add the class if display is 'False' when the page loads, and also to add it if the 'False' radio button is selected.
However, I found that js had a problem reading the value of the input, and thinks that it is true almost all the time, even if the false button is selected. I'm assuming it must be something to do with the fact that the two inputs have the same name?
My question is, how do I ensure that js always picks the input that is currently selected, and will this make sure that it reads the correct value?
UPDATE: I have changed $('input[name="display"] to $('input[name="display"][checked="checked"]'), in an effort to make js home in on whichever radio button is checked. This solves the problem where js did not know which button was checked on page load. However, now it always targets whichever button was checked on page load, instead of the button that's actually checked currently.
Apologies if I seem like a complete novice, but I am, so...
Any and all suggestions on how to better organise my code are welcome; I'm very unfamiliar with best practises in web dev.
Thanks!
Just change the following line in your change event from :
if ($('input[name="display"]').val() === "False") {
to:
if ($(this).val() === "False") {
This will check for the value of the radio button that is current clicked.
I used a combination of #Ehsan's answer, and a partial solution that I included in an update to the the question.
I decided to place the js block in a function, which took the element whose value I was checking as a parameter:
function checkdisplay(dispradio) {
var a = document.getElementById("selectedRoomName");
var b = document.getElementById("selectedRoomArrow");
if ((a) && (b)) {
if (dispradio.val() === "False") {
a.className += " obscured";
b.className += " obscured";
} else {
a.className = a.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
b.className = b.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
}
}
}
Then I called the function in two places like so:
//first for document load
$(document).ready(function () {
checkdisplay($('input[name="display"][checked="checked"]'));
});
and
//and then for change events
$('input[name="display"]').change(function () {
checkdisplay($(this));
});
Seems like [checked="checked"] was needed to let js know which button was checked on page load, but that then needed to be removed for onchange events, or js would target whichever button was checked on page load, rather than the button that was actually checked!
Many thanks for your partial solution #Ehsan, it helped me come up with this one!

Javascript Checkbox Ticked on Load Error

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;

My checkbox doesn't work with loop for to display data

I did the checkbox work good, this is my one:
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
document.getElementById("srt").value = document.getElementById("Ultra").value;
}
else if($(this).prop("checked") == false){
document.getElementById("srt").value = "";
}
});
});
At my display data part, I have the loop for to show all the record. I want after I click the checkbox the value I get from document.getElementById("Ultra").value and display on document.getElementById("srt").value. It work good at 1 record only, the rest I check didn't work. I think the problem is I display it on <input type="text" id="srt"> and the textbox I put in loop with loop for to display database. Any help?
This one is php part:
for ( $v = 0 ; $v < mysql_num_rows($result) ; $v++ )
{
$row = mysql_fetch_assoc($result);
?>
<td><input type="checkbox"/></td>
<?php
echo'<td>'.$row['aaa'].'</td>';
echo'<td>'.$row['bbb'].'</td>';
echo'<td>'.$row['ccc'].'</td>';
echo'<td><input type="text" id="srt"></td>';//////this one to display value i get
echo'<td>'.$row['dddr'].'</td>';
}
The value only display on 1 row only.
One thing I see is you have <input type="text" id="srt"> in each loop. This means your ids are not unique and this could cause problems in the document.getElementById("srt").value = document.getElementById("Ultra").value; call.
Try make ids unique (this means giving a different id for every textbox, maybe something like srt_'.$v.' and also retrieving the correct textbox id in the jquery function)
PS: can you please show also the "Ultra" input in your php code?
Edit: to get the correct textbox you could set an id to your checkbox too and use it to get the correct id of the textbox.
In your page:
echo'<td><input type="checkbox" id='.$v.'/></td>';
and
echo'<td><input type="text" id="srt'.$v.'"></td>';
And in your function
if($(this).prop("checked") == true){
document.getElementById("srt"+this.id).value = document.getElementById("Ultra").value;
}
I did not test it so there could be something to adjust, but the idea is there.
try this..
$(document).ready(function(){
var values = $('input.high_name:checked').map(function () {
return this.value;
}).get();
alert(values);
});
and your checkbox add class name,
<input type="checkbox" value="" name="high[]" class="high_name">

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