If an input has a value, specific radio button should be checked - javascript

I want to check if an input (name="companyname") has a value and if so, it should check a radio button (id="Zakelijk"). If it does not have any value, it should check the other radio button (id="Particulier").
See my current code:
<script type="text/javascript">
function ShowHideDiv() {
var chkYes = document.getElementById("Zakelijk");
var dvPassport1 = document.getElementById("checkzakelijk");
var dvPassport2 = document.getElementById("checkzakelijk1");
var dvPassport3 = document.getElementById("checkzakelijk2");
var display = chkYes.checked ? "block" : "none";
dvPassport1.style.display = display;
dvPassport2.style.display = display;
dvPassport3.style.display = display;
}
</script>
<div class="col-md-12 check-business">
<div class="form-group form-group-xl">
<label for="Particulier"><input type="radio" id="Particulier"checked="checked" name="checkzakelijk" onclick="ShowHideDiv()" />Particulier</label>
<label for="Zakelijk"><input type="radio" id="Zakelijk" name="checkzakelijk" onclick="ShowHideDiv()" />Bedrijf</label>
</div>
</div>
<div class="col-md-12" id="checkzakelijk" style="display:none;">
<div class="form-group">
<label for="inputCompanyName" class="control-label">{$LANG.clientareacompanyname}</label>
<input type="text" name="companyname" id="inputCompanyName" value="{$clientcompanyname}"{if in_array('companyname', $uneditablefields)} disabled="disabled"{/if} class="form-control" />
</div>
</div>

There are other ways, but this should get you going:
$(function() {
if (($("#inputCompanyName").val() || "") != "")
{
$("#Zakelijk").prop("checked", true)
} else {
$("#Particulier").prop("checked", true)
}
});
This is based on your html where the input name='companyname' also has id 'inputCompanyName' and will clear the other radio because they have the same name=
Edit Working jsfiddle: https://jsfiddle.net/76x42os0/4
change input value in the code box (top left) and click run.
Update: Updated the fiddle to the indicated jquery version 3.1.0 and found the newer version of jquery needs id= to match #, while before it matched on name=

If you want to check it when the input is changed you can do
$("input[name='companyname']").change(function(){
var hasValue = $(this).val() === "";
$("#Zakelijk").prop("checked", hasValue);
$("#Particulier").prop("checked", !hasValue);
})
you can optimize the code, but this is more readable.

In case you need the solution in Javascript
if(document.getElementById("inputCompanyName").value !== ""){
document.getElementById("Zakelijk").checked = true;
document.getElementById("Particulier").checked = false;
}
else{
document.getElementById("Particulier").checked = true;
document.getElementById("Zakelijk").checked = false;
}

Here's a working example of what you're after (albeit without your HTML ids/layout in mind, but you can simply change the IDs within).
$("#text-box").on('change', function(){
if($(this).val() != ""){
$('#rd1').prop("checked", true)
}else{
$('#rd2').prop("checked", true)
}
});
https://jsfiddle.net/bm18hmLa/3/
It hooks into the changed event, so it would occur every time the text-box value has been changed.
After thought:
Changing
$("#text-box").on('change', function(){
to
$("#text-box").on('input', function(){
makes it a little "nicer" in terms of responsiveness.
https://jsfiddle.net/bm18hmLa/5/
and here's a version with your ID names too.
https://jsfiddle.net/bm18hmLa/6/

Related

checkbox onclick wont change checked via jscript

I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}

Reveal additional info based on two (out of three) checkboxes JavaScript

I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');

Can't get state of switch with javascript or jquery

I needed a switch button for a project of mine so I searched and found an easy solution at w3schools. The only issue is that I can't catch the state of the switch now.
I created a function that will change the value of an input filed if the switch is toggled on or off.
var checker = false;
function poly_marker_ctrl(categ, t) {
if (checker == false) {
$("display_result").val('is checked');
checker = true;
} else {
$("display_result").val('is unchecked');
checker = false;
}
}
But that doesn't seem to work. Here is the example on jsfiddle.
Thanks for your time.
Try using this.
HTML section :
<div class="col-md-3">
<label class="switch">
<input type="checkbox">
<div class="slider round"></div>
</label>
<input id="display_result" type="text" value="is unchecked" readonly>
<div>
In script :
var switchButton = 'off';
$(".slider").click(function(){
if(switchButton == 'off'){
switchButton = 'on';
$('#display_result').val('is checked');
}else{
switchButton = 'off';
$('#display_result').val('is unchecked');
}
});
And css same as you have shown in fiddle.It will work.

How would I find the label's child? (HTML + JS)

How would I make JS find the child with the class of "money"? I have it coded so that it will find the radio button when clicked. Once it's clicked it will return that radio button and id. But I also need to find the "money" class.
HTML:
<div class="col-sm-4 col-md-2">
<input name="STORAGE" type="radio" id="STORAGE2">
<label class="radio" for="STORAGE2">
<center>
<img src="../images/Parts/Western_Digital_Caviar_Blue_320GB.png" class="comp-img"><br><br>
<p>500GB Western Digital WD5000AAKX 3.5" 7200RPM HDD</p>
<p class="money">+$55</p> <!--THIS IS THE CLASS I AM TRYING TO GET-->
</center>
</label>
</div>
JS:
$(function(){
var cpu = "";
//Controling radio buttons
$('radio').on('click'), function(){
var clickedID = $(this).attr("id");
if (clickedID.substring(1,3) == "CPU") {
if (cpu == "") {
cpu = clickedID;
} else {
}
}
}
});
if your label's for attribute is the value of the radio ID then you can do like this
var el = $('label[for='+clickedID +']').find('.money');
use the jQuery find function $(this).find(".money");
Your syntax is off a little bit, but this should work:
EDIT:
As #empiric has noted, .money is not a child of $('radio'), it is a child $('.radio'), which is not the intended click target.
$('.radio').on('click', function(){
var $this = $(this);
var clickedID = $this.attr("for");
// Child .money element (put this wherever you need it)
var childMoneyEl = $this.find('.money')
if (clickedID.substring(1,3) == "CPU") {
if (cpu == "") {
cpu = clickedID;
}else{
}
}
});

Disable CheckBox Dynamically using JQuery

I have a collection of checkboxes within a form. I am looping through the collection to check and/or disable the checkboxes. The checking works fine; however, I am having an issue with checking if the checkbox is disabled or not. It always return false even when the checkbox is enabled. I looked at the code over and over, and I could not see a anything that could cause this to happen.
Partial HTML File
<label class="col-lg-3"><div style="padding-left:5px;">View Department</div></label>
<div class="col-lg-1"><input id="Accounting" name="Accounting" type="checkbox" /> </div>
<label class="col-lg-3"> Finance</label>
<div class="col-lg-1"><input id="Finance" name="Finance" type="checkbox" /></div>
<label class="col-lg-3"> Marketing</label>
<div class="col-lg-1"><input id="Marketing" name="Marketing" type="checkbox" /></div>
<div class="col-lg-12">
<hr style="width:100%;" />
</div>
//This is how I disable the checkbox
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
if (typeof (e) !== 'undefined') {
if (e) {
switch (e) {
case 'Education':
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id == 'Accounting') || (collection[i].id == 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
break;
}
}
}
//The rendering HTML
<input checked="checked" id="Accounting" name="Accounting" type="checkbox" disabled>
//checking if the field is disabled or not
var isAccountingDisabled = $('#Accounting').is(':disabled');
//The above code always return false. Why is that?
I added a screen shot of the checkbox property showing that the checkbox is automatically checked and disabled. Even though the checkbox is rendering as disabled, the property does not show it as being disabled.
You can't have multiple elements with the same id. In your looping structure you can add the index of the loop also to the id, so that it will be unique. (Accounting1, Accounting2...)
Change your code to something like this
var checkBoxesCollection = $("#yourparentelement").find("input:checkbox[name='Accounting']");
$.each(checkBoxesCollection, function(){
if (this.disabled) {
};
});
http://jsfiddle.net/eanamztz/
Use === instead of ==
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id === 'Accounting') || (collection[i].id === 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
I was not able to read the property using $('#Accounting').is(':checked'); however, I was able to read them using the syntax below.
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
$.each(collection, function (index, item) {
ListDepartments[item.name + "Disabled"] = item.disabled;
})

Categories

Resources