Disable/Enable a text box based on radio/select option selected Javascript - javascript

I am trying to disable an input field in HTML if a radio button has a particular value. I have used Javascript functions for the same.
CODE SNIPPET 1 : (HTML RADIO BUTTON)
<div class="element-radio">
<label class="title">Children</label>
<div class="column column2">
<label>
<input type="radio" name="children" value="Yes" onChange="findselected()"/>
<span>Yes</span>
</label>
</div>
<span class="clearfix"></span>
<div class="column column2">
<label>
<input type="radio" name="children" value="No" checked="checked" onChange="findselected()"/>
<span>No</span>
</label>
</div>
<span class="clearfix"></span>
</div>
<div class="element-number">
<label class="title">No of children</label>
<div class="item-cont">
<input class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />
<span class="icon-place"></span>
</div>
</div>
CODE SNIPPET 2 : (JAVASCRIPT FUNCTION)
<script type="text/javascript">
function findselected() {
if (document.form.children.value == 'No') {
document.form.no_children.disabled=true;
// return false; // not sure this line is needed
} else {
document.form.no_children.disabled=false;
// return false; // not sure this line is needed
}
}
</script>
This does not work in the required way. Is there a better way to go about doing the same? I'm fairly new to Javascript so I wouldn't be able to implement a complicated code.

Update your script with the following code:
function findselected() {
var result = document.querySelector('input[name="children"]:checked').value;
if(result=="Yes"){
document.getElementById("inputtext").setAttribute('disabled', true);
}
else{
document.getElementById("inputtext").removeAttribute('disabled');
}
}
And add id attribute in your input control as id="inputtext".
<input id="inputtext" class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />

Related

How to read multiple checkboxes(and data associated with it)?

I have a form with multiple checkboxes and each checkbox as an input field associated with it that'll activate once you check the checkbox.
I've got the frontend working just fine, but I was wondering how can I read in my PHP which checkboxes were checked along with their respective input fields (and some have a radio button too in addition to the input field)
Here's what each individual checkbox in my form looks like:
<!-- Option1 -->
<div class="form-row">
<div class="form-group col-md-8">
<div class="form-check">
<input class="form-check-input showman" type="checkbox" onchange="showqt()" value="Button Chicken Amritsari" id="c1">
<label class="form-check-label" for="c1">
Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>
</label>
</div>
</div>
<div class="form-group col-md-4" id="ifYes" style="display: none; float:right;">
<!-- <label for="qtcounter">Quantity:</label> -->
<div class="input-group" id="qtcounter">
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="1" name="quantity" class="quantity-field">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
</div>
</div>
<!-- Option 1 ends -->
I haven't wrapped my head around the PHP yet but previously to read multiple checkboxes I put them all in an array in the name field and read that array in PHP. However, that was without the added complication of each checkbox having input field.
Does anyone have any idea how to do this?
You want to use an associative array for both the inputs and the checkboxes.
<!-- Option1 -->
<div class="form-row">
<div class="form-group col-md-8">
<div class="form-check">
<input class="form-check-input showman" type="checkbox" name="items[1][chosen]" onchange="showqt()" value="Button Chicken Amritsari" id="c1">
<label class="form-check-label" for="c1">
Button Chicken Amritsari<i><br>(Boneless) Serves 2<br>INR 290</i>
</label>
</div>
</div>
<div class="form-group col-md-4" id="ifYes" style="display: none; float:right;">
<!-- <label for="qtcounter">Quantity:</label> -->
<div class="input-group" id="qtcounter">
<input type="button" value="-" class="button-minus" data-field="items[1][quantity]">
<input type="number" step="1" max="" value="1" name="items[1][quantity]" class="quantity-field">
<input type="button" value="+" class="button-plus" data-field="items[1][quantity]">
</div>
</div>
</div>
<!-- Option 1 ends -->
For option 2 use items[2][chosen] and items[2][quantity], etc.
Note that must specify the index and can't use []. Otherwise, the index of quantity will not match the chosen item.
In php you can loop through the items and ignore the items that aren't chosen.
foreach ($_POST['items'] as $item) {
if (!isset($item['chosen'])) continue; // Skip items that aren't chosen.
echo $item['quantity'] . ' ' . $item['chosen'] . "\n";
}

Pass value from one field to another

Got a 3 selection radio button options and also a number field, in case somebody wants to select more than radio buttons can offer. And i'm trying to pass a radio button value to the number field when radio value is changed.
Here is my html code for it
<!-- this is main add to cart form -->
<form>
<!-- and this is secondary form for radio buttons, so, only one could be selected -->
<form class="quanform">
<div class="pricelinewrap">
<div class="priceline">
<div class="pricelinecellval">
<input type="radio" id="quanlineradio1" value="1" name="quanline" />
</div>
</div>
</div>
<div class="pricelinewrap">
<div class="priceline">
<div class="pricelinecellval">
<input type="radio" id="quanlineradio2" value="2" name="quanline" />
</div>
</div>
</div>
<div class="pricelinewrap">
<div class="priceline">
<div class="pricelinecellval">
<input type="radio" id="quanlineradio3" value="3" name="quanline" />
</div>
</div>
</div>
</form>
<div class="newquanfield tablecell almiddle">
<input type="number" min="1" size="2" class="quantity" name="quantity" id="quantity" value="2" />
</div>
</form>
And this is my jquery code for it
$("form.quanform .pricelinewrap .priceline .pricelinecellval input[type=radio]").each(function(){
$(this).click(function(){
var quanval = $(this).val();
$(this).parents().find(".newquanfield input[type=number]").val(quanval);
});
});
Nothing happens and there are no errors in the console
The problem lies purely in your selector:
$("form.quanform) won't work, as your <form class="quanform"> is wrapped inside another <form>, which is invalid markup; <form> cannot be nested inside another <form>.
Because the 'desired' markup is invalid, it actually never gets added to the DOM. You can confirm this by viewing the source yourself with CTRL + U - <form class="quanform"> doesn't exist. Thus, you cannot target it with jQuery.
You can validate your markup with the W3 Validation service to ensure that your HTML is indeed valid, ensuring that your jQuery selectors work the way you expect.
As for your current structure, you can omit the .quanform component, and simply use $("form .pricelinewrap .priceline .pricelinecellval input[type=radio]"), which will work based off of the outer <form> element (which does indeed exist in the DOM).
This can be seen working in the following example:
$("form .pricelinewrap .priceline .pricelinecellval input[type=radio]").each(function() {
$(this).click(function() {
var quanval = $(this).val();
$(this).parents().find(".newquanfield input[type=number]").val(quanval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- this is main add to cart form -->
<form>
<!-- and this is secondary form for radio buttons, so, only one could be selected -->
<form class="quanform">
<div class="pricelinewrap">
<div class="priceline">
<div class="pricelinecellval">
<input type="radio" id="quanlineradio1" value="1" name="quanline" />
</div>
</div>
</div>
<div class="pricelinewrap">
<div class="priceline">
<div class="pricelinecellval">
<input type="radio" id="quanlineradio2" value="2" name="quanline" />
</div>
</div>
</div>
<div class="pricelinewrap">
<div class="priceline">
<div class="pricelinecellval">
<input type="radio" id="quanlineradio3" value="3" name="quanline" />
</div>
</div>
</div>
</form>
<div class="newquanfield tablecell almiddle">
<input type="number" min="1" size="2" class="quantity" name="quantity" id="quantity" value="2" />
</div>
</form>
Hope this helps! :)

checkbox validation angularjs

I have multiple checkboxes for a question.Atleast one checkbox needs to be selected.If none of the checkboxes get selected form should through validation error.Did i miss anything. Any ideas on how I would be able to achieve this behaviour?
My .JS code:
$scope.onCheckBoxSelected=function(){
var flag=false;
for(var key in selectedOptions){
console.log('Key -' +key +' val- '+selectedOptions[key]);
if(selectedOptions[key]){
flag=true;
}
}
if(!flag){
selectedOptions=undefined;
}
};
below is my html code :
<div class="grid">
<div class="col flex-10 mandatoryField" ng-class="{error: (!selectedOptions && formMissingFields)}">Hello please select atleast one</div>
<div class="col flex-2">
</div>
<div class="col flex-5">
<div style="padding-top: 2px">
<input type="checkbox" name="apple" title="Select type" value="apple" ng-model="apple" ng-change="onCheckBoxSelected()">apple
</input>
</div>
<div style="padding-top: 2px">
<input type="checkbox" name="orange" title="Select type" value="orange" ng-model="orange" ng-change="onCheckBoxSelected()">orange
</input>
</div>
<div style="padding-top: 2px">
<input type="checkbox" name="banana" title="Select type" value="banana" ng-model="banana" ng-change="onCheckBoxSelected()">banana
</input>
</div>
</div>
</div>
You can keep it simpler, without the need of the ngChange event.
<div ng-class="{error: !apple && !orange && !banana">Hello please select atleast one</div>
It's best practice to use the AngularJS forms for checkbox validation - it will also help you if you intend on extending your form. You will have to refactor your code to use this functionality.
<ng-form name="myForm">
<span style="color:red;" ng-show="myForm.$invalid">Please select one</span>
<br />
<!-- your checkbox values will be in "choices" -->
<p ng-repeat="choice in choices">
<label class="checkbox" for="{{choice.id}}">
<input type="checkbox" value="{{choice.id}}" ng-click="updateQuestionValue(choice)" ng-model="choice.checked" name="group-one" id="{{choice.id}}" ng-required="value.length==0" /> {{choice.label}}
</label>
</p>
<input type="submit" value="Send" ng-click="submitSurvey(survey)" ng-disabled="myForm.$invalid" />
</ng-form>
See this fiddle - note that it uses underscore.js. Also, this question may help.

Enabling multiple textboxes with a corresponding multiple checkbox using a single jQuery function

I have 4 multiple check boxes which each one of them is specifically correspondent to 4 text-boxes. I need to enable the disabled texbox when the corresponding checkbox is checked. I wrote a same function for each checkbox's onclick event in html tag itself as onclick="document.getElementById('txtLrgPrc').disabled=!this.checked;" .
But I need to automate this by calling a function only once by sending the parameters of textboxes and heckboxes(i.e. id or name,,) to my js file using jQuery. Can anyone help me for refining this please?
Here is the code which I am currently using and it works finely.
jsp page:
<div class="row item-tbl-row" id="addItmChkbxReg">
<div class="col-xs-5">
<label class="checkbox-inline">
<form:checkbox value="regular" class="checkbox sizechkbx" path="size" label="Regular" id="chkReg" onclick="document.getElementById('txtRegPrc').disabled=!this.checked;"/>
</label>
</div>
<div class="col-xs-7">
<form:input type="text" class="form-control price" path="price" id="txtRegPrc" disabled="true"/>
</div>
</div>
<div class="row item-tbl-row" id="addItmChkbxMed">
<div class="col-xs-5">
<label class="checkbox-inline">
<form:checkbox value="medium" class="checkbox sizechkbx" path="size" label="Medium" onclick="document.getElementById('txtMedPrc').disabled=!this.checked;"/>
</label>
</div>
<div class="col-xs-7">
<form:input type="text" class="form-control price" path="price" id="txtMedPrc" disabled="true"/>
</div>
</div>
<div class="row item-tbl-row" id="addItmChkbxLrg">
<div class="col-xs-5">
<label class="checkbox-inline">
<form:checkbox value="large" class="checkbox sizechkbx" path="size" label="Large" onclick="document.getElementById('txtLrgPrc').disabled=!this.checked;"/>
</label>
</div>
<div class="col-xs-7">
<form:input type="text" class="form-control price" path="price" id="txtLrgPrc" disabled="true"/>
</div>
</div>
You can automate like the following.
<script type="text/javascript">
$(document).ready(function () {
$(".checkbox").click(function () {
$(this).parent().parent().next().find(".form-control").prop("disabled", !$(this).prop("checked"));
});
});
</script>
Also, remove the click event of the checkboxes.
Another solution:
<script type="text/javascript">
function C(t, textBoxId) {
$("#" + textBoxId).prop("disabled", !$(t).prop("checked"));
}
</script>
<form:checkbox value="regular" id="chkReg" onclick="C(this, 'txtRegPrc')"/>

Javascript hide/show questions depending on user input values

I am trying to hide and/or show form elements when a user selects certain values.
For example, if the user selects "yes" to the consent question, I need it to show a few questions, However, if they change their response to the consent question, I need it to hide those questions.
Here is what I have come up with so far...
$(document).ready(function () {
var input = document.getElementById('consent');
var consent_responses = [{ "0": hideConsent },{ "1": showConsent }];
input.addEventListner('click', function () {
var consent_response;
if (consent_responses[this.value]) {
content_response = consent_responses[this.Function()]
}
else {
content_response = consent_responses[this.Function]
}
});
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
function hideConsent(){
$("#date").hide(),
$("#referrer").hide(),
$("#f_name").hide(),
$("#phone_num").hide(),
$("#leave_msg").hide(),
$("#email").hide(),
}; });
Fiddle here: http://jsfiddle.net/7jX47/1/
You could do it like this: JSFiddle
Basically I only fixed a few typos (did you actually try your code before you posted here?) and added event listeners to the radio buttons with
document.getElementById(...).addEventListener(...)
I also gave your radio buttons unique IDs.
This can be simplified:
var input = document.getElementById('consent');
// Let's use the value as key, and the functions as values
var consent_responses = {
"0" : hideConsent,
"1" : showConsent
};
input.addEventListener("click", function () {
// Get the appropriate function given the value, and invoke it
consent_responses[this.value]();
});
function hideConsent() {
// ...
}
function showConsent() {
// ...
}
It's better to envelop your questions (that needs to be hidden) by a div with a class ".hidden" or style "display: none;". And simplify your code by simply asking that div to show() or hide() when needed.
Like so:
<form id="screening">
<div class="col-md-12 col-sm-12 col-xs-12 nopad" id="create">
<div class="form-group text-center">
<b>Do you agree to answer the screening questions?</b><br />
<div class="radio" id="consent">
<label>
<input type="radio" name="consent" id="consent" value="1">
Yes, I consent
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="consent" id="consent" value="0">
No, I do not consent
</label>
</div>
</div>
<!-- simplify by using this -->
<div id="questions" style="display: none;">
<div class="form-group" id="date">
<label for="date">What is today's date?</label>
<input type="date" class="form-control" id="date" name="date" />
</div>
<div class="form-group" id="referrer">
<label for="referrer">How did you hear about us/our studies?</label>
<select class="form-control" name="referrer" id="referrer">
<option></option>
<option value="1">Flyers</option>
<option value="2">Print Media</option>
<option value="3">A friend</option>
<option value="4">Online (e.g., Craigslist)</option>
<option value="5">Other</option>
</select>
</div>
<div class="form-group" id="other_explain">
<label for="other_explain">Please specify other source.</label>
<textarea class="form-control" rows="3" id="other_explain" name="other_explain"></textarea>
</div>
<div class="form-group" id="f_name">
<label for="f_name">What is your first name?</label>
<input type="text" class="form-control" id="f_name" name="f_name" />
</div>
<div class="form-group" id="phone_num">
<label for="phone_num">What is a phone number at which you can be contacted? </label>
<input type="tel" class="form-control" id="phone_num" name="phone_num" />
</div>
<div class="form-group" id="leave_msg">
<label for="leave_msg">If we call and you are not available, may we leave a message?</label><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="1">
Yes
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="0">
No
</label>
</div>
</div>
<div class="form-group" id="email">
<label for="email">What is an e-mail at which you can be contacted?</label>
<input type="email" class="form-control" id="email" name="email" />
</div>
</div>
</div>
</form>
and in your javascript instead of using this:
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
you use:
function showConsent(){
$("#questions").show(),
};

Categories

Resources