JavaScript help needed - javascript

hello i'm using this code for publishing important messages on my applications message wall, i'm using a checkbox for publishing important message on message wall. the problem is that after publishing important message it will again publish the important message without clicking on checkbox, means the checkbox remains true after publishing the important message. please help me for this.
and my code is:
<div class="checkbox" id="checkboxShow" name="userCheckList1" style="display:block;" onclick="importantChkBoxChange(userCheckListShow.checked);">
<input type="checkbox" name="userCheckList1" id="userCheckListShow" unchecked="unchecked"
onchange="importantChkBoxChange(userCheckList.checked);"/>
</div>
<div class="checkbox" id="checkboxHide" name="userCheckList1" style="display:none;" onclick="importantChkBoxChange(userCheckListHide.checked);">
<input type="checkbox" name="userCheckList1" id="userCheckListHide" unchecked="unchecked"
onchange="importantChkBoxChange(userCheckListHide.checked);"/>
</div>
<span class="fl" style="margin:3px 0px 0 0;" ><#spring.message "label.employee.home.Important"/></span>
and the script used for this is:
function importantChkBoxChange(chkBoxStatus){
if(chkBoxStatus == true){
document.forms['messageWallForm'].elements['important'].value="checked";
}else if(chkBoxStatus == false){
document.forms['messageWallForm'].elements['important'].value="unchecked";
}
}

Ok, first unchecked is not a property of input. You can have <input type="checkbox" checked="checked" /> if you want to be XML conscious, or you can simply omit the ="checked": <input type="checkbox" checked />, but unchecked is default, so there is no way to us an unchecked attribute.
Second, I noticed that there are variables userCheckListHide and userCheckListShow, but I don't see a declaration of those variables. Are you sure that they exist? Was userCheckListShow = document.getElementById("userCheckListShow") called after the input was created? Otherwise you're dealing with null values.
Third, with checkboxes and radio buttons, you're not interested in the value, so much as you are interested in whether they are checked. You could re-write your function:
// changed the variable name so that it wouldn't scroll. Your var. name was fine.
function importantChkBoxChange(stat){
// since your test is if(checked) set it to checked otherwise set it to
// unchecked, you can simply set the checked property directly.
document.forms['messageWallForm'].elements['important'].checked = stat;
}
As a side note, if you want this to reflect whether either of the cb's in your question are selected, then both onchange handlers should be:
importantChkBoxChange(userCheckList.checked || userCheckListHide.checked);

I dont know where to begin , but here are a few pointers .
A checkbox is not checked/unchecked by changing it's value . It has a checked attribute .Something like document.getElementById('checkBoxId').checked=true
Use DOM ids to refer to your DOM elements .Ideally .
if(chkBoxStatus == true) is redundant
there's no unchecked attribute for checkboxes
if you want to transmit the checked status of a checkbox to a js function on an event (like onchange) , you can do like onchange="foo(this.checked)"

Related

Variable not changing value on checkbox condition

This section uses a checkbox to select your extras, once selected you move onto the next step and it will display your choice in a header called checkout[itemname]. When a check box is selected it changes a variable from false to true however my code doesn't seem to be doing that.
I will show an example section of the user selecting "Neck Tie" from the list of extras.
var hasNeckTie = false;
if (hasNeckTie = true) {
document.getElementById("checkoutnecktie").innerHTML = "Neck Tie";
}
<div class="three columns bear">
<h3>Matching Tartan Scarf (£2.50)</h3>
<label>
<input type="checkbox" autocomplete="off" name="scarf" id="scarf" value="2.5" />
<img src="Images/Scarft.png">
</label>
<p>Personalise your bear with a matching tartan scarf. It gets cold up here in Scotland, and this is the best way to keep your bear warm.</p>
</div>
<div id="checkoutnecktie"></div>
Any ideas why this code isn't running properly?
Your problem starts where you are using = instead of == in your if statement.
You are also trying to set the HTML value of an element which does not exist.
document.getElementById("checkoutnecktie").innerHTML = "Neck Tie";
You need to change "checkoutnecktie" to an element ID which exists.
You would need to hook an event to the checkbox.
You can do this with jQuery like so
$('#scarf').change(function(){
if($(this).is(":checked")) {
$('#checkoutnecktie').text('Neck tie');
}
}
Also like the other answer states, set the text to an element that exists.

checkbox set to checked = false not working

I'm generating an HTML input with checked="false", however the checkbox is showing up checked.
I did the following in the javascript console and can't quite figure out whats going on. The resulting HTML after using .prop() to set the value to false looks the same except now the checkbox is not checked on the form.
> $(':input[checked]').prop('checked');
< true
> $(':input[checked]')
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]
> $(':input[checked]').prop('checked',false);
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]
I'm under the impression that I should just be setting checked="checked" OR not including the checked property at all if its false is that best practice? Either way I'd like to know what's going on in the above code.
Don't put checked="false"
You only put checked="checked" for valid XHTML, otherwise you'd do
<input type="checkbox" checked>
The browser doesn't care what value is assigned to checked attribute, as soon as it sees checked in the checkbox input tag, it's flagged as checked.
$(document).ready(function () { $(e).prop("checked", false);}
// "e" refers to button element
How to Uncheck in this case, example my code is: (see below)
if(previousHighlightedCheckbox!=null) {
console.log(sent.id, previousHighlightedCheckbox); // current checkbox and previous check box values are different.
document.getElementById(previousHighlightedCheckbox).checked = false; // still this does not uncheck previous one
}

Check a radio button with javascript

For some reason, I can't seem to figure this out.
I have some radio buttons in my html which toggles categories:
<input type="radio" name="main-categories" id="_1234" value="1234" /> // All
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category
The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234 to be set checked radio button, because this is the default checked radio button.
I have tried versions of this (with and without jQuery):
document.getElementById('#_1234').checked = true;
But it doesn't seem to update. I need it to visibly update so the user can see it.
Can anybody help?
EDIT: I'm just tired and overlooked the #, thanks for pointing it out, that and $.prop().
Do not mix CSS/JQuery syntax (# for identifier) with native JS.
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
If you want to set the "1234" button, you need to use its "id":
document.getElementById("_1234").checked = true;
When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector() and .querySelectorAll().
Today, in the year 2016, it is safe to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):
document.querySelector("input[name=main-categories]:checked").value
Easiest way would probably be with jQuery, as follows:
$(document).ready(function(){
$("#_1234").attr("checked","checked");
})
This adds a new attribute "checked" (which in HTML does not need a value).
Just remember to include the jQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
By using document.getElementById() function you don't have to pass # before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo:
JSFiddle
I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:
var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
if (response["reload_mode"] == "Periodic") {
document.querySelector('input[name=reload_mode][value="Periodic"]').click();
} else if (response["reload_mode"] == "Page Bottom") {
document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
} else {
document.querySelector('input[name=reload_mode][value="Both"]').click();
}
});
Where the associated code to SAVE the value was:
reload_mode: document.querySelector('input[name=reload_mode]:checked').value
Given HTML like the following:
<input type="radio" id="periodic" name="reload_mode" value="Periodic">
<label for="periodic">Periodic</label><br>
<input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
<label for="bottom">Page Bottom</label><br>
<input type="radio" id="both" name="reload_mode" value="Both">
<label for="both">Both</label></br></br>
It seems the item.checked property of a HTML radio button cannot be changed with JavaScript in Internet Explorer, or in some older browsers.
I also tried setting the "checked" attribute, using:
item.setAttribute("checked", ""); I know the property can be set by default,
but I need just to change the checked attribute at runtime.
As a workarround, I found another method, which could be working. I had called the item.click(); method of a radio button. And the control has been selected. But the control must be already added to the HTML document, in order to receive the click event.

Radio button on/off trigger works only one way

So this is the dumbest thing I've struggled with in awhile. I cannot get the state of a simple radio button set to toggle something on the page.
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" id="completeSw" name="completeSw" value="0" checked="checked"/>No<br/>
So you can see here an extremely simple yes/no radio button set to toggle an action. It needs to serve two purposes: to flag a yes/no value (1/0) in the POST data, and ideally trigger an action on the page using JS/jQuery. I'm having trouble with the latter.
The default state is "No"; if I click "Yes" I can retrieve an onchange or onclick event state and make something happen. However, this is a one-way switch; I cannot retrieve a state going back to the "No" selector once I've gone to "Yes". What I need to be able to do is show / hide an element on the page depending on what choice they've made in this radio set. If I click "Yes", I can trigger the action and see the page change. Once I click "No", however, it acts as if there was no state change and I cannot perform an action i.e. hide the element again.
I've tried variations on retrieving the "checked" state, the radio pair value, etc, e.g.
$("#completeSw").change(function(e){
alert( $(this).attr("checked") ); // only triggers when "Yes" is selected
});
Perhaps I should not be using a yes/no radio pair, but instead be using a single checkbox? Seems more user-friendly and elegant this way (radio buttons) to me.
IDs must be unique, so it will only ever find the first one on your page. Use a class instead.
Really, ID's must be unique, but you don't need 2 ID's. You'll only monitor changes in one radio. For example - "Yes" value
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" name="completeSw" value="0" checked="checked"/>No<br/>
And the you'll process the checked attribute of only this element. True - "Yes", False - "No"
Some browsers don't do anything when alert(message), message=null. And since an unchecked field has no checked-attribute, that could be the thing :).
Try:
alert('Checked: '+$(this).attr("checked"));
This is separate, but you're kinda using the label wrong also. The label is meant to extend the click area so someone could click on the word 'Yes' and the radio button will activate. Hopefully this helps you out a little.
<span>Completed?</span>
<input type="radio" id="completeSwYes" name="completeSw" value="1"/><label for="completeSwYes">Yes</label>
<input type="radio" id="completeSwNo" name="completeSw" value="0" checked="checked"/><label for="completeSwNo">No</label><br/>
<script type="text/javascript" charset="utf-8">
// If the radio button value is one then this evaluates to true.
var completeSW;
jQuery("input[type='radio'][name='completeSw']").change(function() {
completeSW = (jQuery(this).val() == 1);
alert("completeSW checked? " + completeSW);
});
</script>

odd behavior when checking if radio button selected in jQuery

I had the following check in my jQuery which I thought was working fine to see if a radio button was checked.
if ($("input[#name='companyType']:checked").attr('id') == "primary") {
...
}
Here's the radiobuttons:
<p>
<label>Company Type:</label>
<label for="primary"><input onclick="javascript: $('#sec').hide('slow');$('#primary_company').find('option:first').attr('selected','selected');" type="radio" name="companyType" id="primary" checked />Primary</label>
<label for="secondary"><input onclick="javascript: $('#sec').show('slow');" type="radio" name="companyType" id="secondary" />Subsidiary</label>
</p>
Then, it suddenly stopped working (or so I thought). I did some debugging and finally realized that it was returning an id of "approved_status". Elsewhere on my form I have a checkbox called "approved_status". I realized that when I originally tested this, I must have testing it on records where approved_status is false. And, now most of my approved_statuses are true/checked.
I changed the code to this:
var id = $("input:radio[#name='companyType']:checked").attr('id');
alert(id);
if (id == "primary") {
And it's now properly returning "primary" or "secondary" as the id.
So, it is working, but it seems that it's not checking the name at all and now just checking radio buttons. I just want to know for future use, what's wrong with the original code b/c I can see possibly having 2 different radio sets on a page and then my new fix probably wouldn't work. Thanks!
Try this:
var id = $("input[name='companyType']:checked").attr('id');
alert(id);
if (id == "primary") {

Categories