Radiobutton when selected show div and make required - javascript

I have a Magento website and there are some delivery options when ordering a product.
There are 2 methods available.
- pick up yourself
- deliver
When you choose radiobutton "deliver" some div with a textarea is visible.
This textarea needs to be required.
But when you select radiobutton "pick up yourself" the textarea is invisible and needs to be NOT required anymore.
I made a fiddle of the items
Can anyone help me with how to do this?
HTML:
<h2>Select delivery method</h2>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method"> pick up
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method"> deliver
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>

If you are after a pure js version you can use this method:
function check() {
var items = document.getElementsByName('shipping_method');
var v = null;
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
v = items[i].value;
break;
}
}
var required = (v == "tablerate_bestway");
document.getElementById("deliv-hold").style.display = required ? "block" : "none";
if (required) {
document.getElementById("shipping_arrival_comments").setAttribute("required", true);
} else {
document.getElementById("shipping_arrival_comments").removeAttribute("required");
}
}
http://jsfiddle.net/gv7xh4cg/9/
Basically, iterate over items of the same name and see if they are selected, if they are grab the value from it and use that to show or hide the comments div.
Cheers,
Ian

Here you can see an example of code to do so :
$(document).ready(function() {
var submitMessage = "";
$(":radio").change(function() {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
$("#deliv-hold").hide(250);
}
else {
$("#deliv-hold").show(250);
}
});
$("form").submit(function(e) {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
submitMessage = "Your command is in process. Thank you for purshasing.";
}
else {
if ($("#shipping_arrival_comments").val().length < 1) {
e.preventDefault();
alert("Field 'delivery date and time' missing.");
submitMessage = "";
}
else {
submitMessage = "Deliver is on his way. Thank you for purshasing.";
}
}
if (submitMessage != "") {
alert(submitMessage);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title> Test check </title>
<meta charset = "utf-8" />
</head>
<body>
<span>Choose your delivery method :</span>
<form>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method">
<label for="s_method_freeshipping_freeshipping">Pick up yourself</label>
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method">
<label for="s_method_tablerate_bestway">Deliver</label>
<br />
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
<input type = "submit" id="submit_delivery" name = "submit_delivery" />
</form>
</body>
</html>
I used JQuery include (see below the code the script include) to use the DOM selector which is easier to use than plain javascript.

I updated your fiddle (it also makes the textarea required):
http://jsfiddle.net/gv7xh4cg/4/
You should include jQuery for:
$('input.radio').click(function(){
var selectedOption = $(this).val();
var delivlHold = $('#deliv-hold'),
comments = $('#shipping_arrival_comments');
if(selectedOption === 'freeshipping_freeshipping') {
delivlHold.show();
comments.prop('required',true);
} else {
delivlHold.hide();
comments.prop('required',false);
}
});
and than add display: none:
#deliv-hold{padding-top:20px; display: none}
It does what you asked for.

Related

how to count check checkboxes in a specific div JAVASCRIPT

I would like to alert the amount of check boxes that are checked in a specific div (not the ones in the <head>!), here is the code :
HTML
<div class="changer">
<label><input id="mode" type="checkbox" name="mode" value="Mode" onclick="mode()" />Mode</label><br />
<label><input id="map" type="checkbox" name="map" value="Map" onclick="map()"/>Map</label><br />
<label><input id="joueurs" type="checkbox" name="joueurs" value="Joueurs" onclick="joueurs()" />Joueurs</label><br />
<label><input id="points" type="checkbox" name="points" value="Points" onclick="points()" />Points</label><br />
</div>
</head>
<body>
<div id="text">
</div>
</body>
<button id="send" onclick="send()">Envoyer</button>
Javascript
function joueurs() {
if((document.getElementById("joueurs").checked == true)) {
joueursall.style.display = 'inline';
text.style.display = 'inline';
}
else {
if((document.getElementById("mode").checked == true)) {
modeall.style.display = 'none';
document.getElementById('mode').checked = false;
}
joueursall.style.display = 'none';
text.style.display = 'none';
}
}
document.getElementById("playerlist").addEventListener("change", function() {
var selected = this.value;
document.getElementById("text").innerHTML = "";
var html = '';
for (var i = 0; i < selected; i++) {
html += '<div class="grpjoueur"> <span class="sub-text">Player</span> <label><input type="checkbox" name="botbot" value="BOT"/>BOT</label </div>';
}
document.getElementById("text").innerHTML = html;
});
Here is the Javascript, it adds 'Joueurs' Dropdownlist if Joueurs is checked and then pop X times something, including a check box, according to the number selected in the Dropdownlist in the #text div
I tried multiple things but always return 0 or all the checkboxes...
In vanilla JS you can use querySelectorAll to query the checkboxes, and then .length to get the number of checkboxes.
var checkboxes = document.querySelectorAll("input[type='checkbox']");
alert(checkboxes.length);
CodePen Demo
If you want to alert only the length of the checked checkboxes, you can query them like this:
var checkedInputs = document.querySelectorAll("input:checked");
alert(checkedInputs.length);
CodePen Demo
when you click on the button, it will alert the number of checked boxes

Checkbox select deselect all and perform function

I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine. What I would like to do is have the checkboxes perform their functions when select all is clicked. It works at the moment, but only when I refresh the page. I would like it to happen when select all is clicked.
Here's what I've been playing with so far:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
this.click();
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 1
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 2
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 3
</label>
<button type="button" class="js-button">Check/uncheck all</button>
<div class="js-result"></div>
JSFiddle
CheckBox should be handled with onchange event.
Below code I am firing an event whenever the checkbox checked programmatically.
Below code may help you
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
/* this.click(); */
this.fireevent('onChange');
/* or you can call this.onChange(); */
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
In case you are using only java script.
Below is the very simple running example. which consumes short time without any use of external library as JQuery
HTML code
<html>
<head>
<title>test</title>
<script>
function amend(a)
{
document.getElementById("ta").value += a;
}
function checkAll()
{
var textboxes = document.getElementsByClassName("cb");
for(i=0;i<textboxes.length;i++)
{
textboxes[i].checked=true;
textboxes[i].onchange();
}
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="ta">
Below the outputs
</textarea>
<div id="checkdiv">
<input type="checkbox" onChange="amend(this.value)" value="data to add 1" class="cb">First</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 2" class="cb">Second</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 3" class="cb">Third</input>
<br>
<input type="checkbox" onChange="checkAll()">Check all</input>
</div>
</body>
</html>

How to pass a variable from JavaScript to HTML?

I have a JavaScript defined in my file as follows:
<script language="javascript">
var transports = "<%=api.transports%>";
var httpsTransport;
var httpTransport;
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https") {
httpsTransport="https";
} else if (splittedTransports[i]=="http") {
httpTransport="http";
}
}
</script>
And I would like to read it in my HTML page like:
<div class="checkbox">
<label class="checkbox inline">
<input type="checkbox" id="transport_http" name="transport_http" value="http" <%if(httpTransport=="http"){%>checked<%}%> />
</label>
<label class="checkbox inline">
<input type="checkbox" id="transport_https" name="transport_https" value="https" <%if(httpsTransport=="https"){%>checked<%}%>/>
</label>
</div>
But now I get an error that states:
org.mozilla.javascript.EcmaError: ReferenceError: "httpTransport" is not defined.
What am I doing wrong here?
I want to allow user to select an checkbox and save the form, and when he tries to edit the form, I want to show what he has saved in his previous operation.
So, when he tries to edit I try to read the values form backend and would like to show that particular option as checked.
<script language="javascript">
var transports = "<%=api.transports%>";
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https"){
document.getElementById("transport_https").checked = true;
}else if (splittedTransports[i]=="http"){
document.getElementById("transport_http").checked = true;
}
}
</script>
HTML :
<div class="checkbox">
<label class="checkbox inline " >
<input type="checkbox" id="transport_http" name="transport_http" value="http" />
</label>
<label class="checkbox inline" >
<input type="checkbox" id="transport_https" name="transport_https" value="https"/>
</label>
</div>
The variables in your code are declared, but not defined.
Give them a random value first, and then update it with the if
<script language="javascript">
var transports = "<%=api.transports%>";
var httpsTransport = 'no';
var httpTransport = 'no';
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https"){
httpsTransport="https";
}else if (splittedTransports[i]=="http"){
httpTransport="http";
}
}
</script>

Enable a text box only when 1 of the radio button is clicked

I have 2 radio button ie yes and no. When I select yes the text box as to get enabled. When i click no the text box as to be disabled. How to enable the text box when I click on Yes. Here is the code. Please tel me how to enable and disable it using javascript.
<script type="text/javascript">
$(function() {
$("#XISubmit").click(function(){
var XIyop= document.forms["XIForm"]["XIyop"].value;
var XIForm = $('form[name=XIForm]');
var XIAlmnus = XIForm.find('input[name=XIAlmnus]:checked').val();
if (XIAlmnus == null || XIAlmnus == "")
{
alert("Please select Parent is an Alumnus (old Boy) of this school");
return false;
}
document.getElementById("XIForm").submit();
});
</script>
<!-- html code-->
<html>
...
<label>Parent is an Alumnus (old Boy) of this school </label> &nbsp&nbsp
<input type='radio' name='XIAlmnus' value='Yes' id="XIyes"/>Yes
<input type='radio' name='XIAlmnus' value='No' id="XIno"/>No</td>
<label>If Yes, Year of passing </label> &nbsp&nbsp
<input type="textbox" name="XIyop" id="XIyop" >
...
</html>
I think, you should use some general handler for this: http://jsfiddle.net/maximgladkov/MvLXL/
$(function() {
window.invalidate_input = function() {
if ($('input[name=XIAlmnus]:checked').val() == "Yes")
$('#XIyop').removeAttr('disabled');
else
$('#XIyop').attr('disabled', 'disabled');
};
$("input[name=XIAlmnus]").change(invalidate_input);
invalidate_input();
});
first make the text box disabled.
<input type="textbox" name="XIyop" id="XIyop" disabled>
When radio button clicked, check and enable it.
if(document.getElementById('XIyes').checked) {
document.getElementById("XIyop").disabled = false;
}else if(document.getElementById('XIno').checked) {
document.getElementById("XIyop").disabled = true;
}
$(function() {
$('input[name="XIAlmnus"]').on('change', function() {
if ($(this).val() == 'Yes') {
$("#XIyop").prop('disabled', false);
} else {
$("#XIyop").prop('disabled', true);
}
});
});
<input type="textbox" name="XIyop" id="XIyop" disabled>
if(document.getElementById('XIyes').attr('checked')) {
document.getElementById("XIyop").disabled = 'true';
}
if(document.getElementById('XIno').attr('checked')) {
document.getElementById("XIyop").disabled = 'false';
}
HTML:
<label>Parent is an Alumnus (old Boy) of this school </label> &nbsp&nbsp
<input type='radio' name='XIAlmnus' value='Yes' id="XIyes"/>Yes
<input type='radio' name='XIAlmnus' value='No' id="XIno"/>No
<br/>
<label>If Yes, Year of passing </label> &nbsp&nbsp
<input type="textbox" name="XIyop" id="XIyop" disabled>
JS:
document.getElementById('XIyes').onchange = displayTextBox;
document.getElementById('XIno').onchange = displayTextBox;
var textBox = document.getElementById('XIyop');
function displayTextBox(evt){
if(evt.target.value=="Yes"){
textBox.disabled = false;
}else{
textBox.disabled = true;
}
}
Please see working demo here. Thank you I hope this will help you.

Checkbox and text field, if one is selected or has value require other(s)

I have two checkboxes in a group and one text input. If one (or both) of the checkboxes are selected I need to have the text input be required, as well as if the text input has text I need at least one of the checkboxes to be required. Another problem I'm having it that it's using a custom templating engine (PHP backend) and is a pain to configure and get the attributes correct, another issue is it's all referenced by the name attribute and this is why I'm using a HTML5 data-group for the checkbox options which I think it working.
Any help in getting this to work, combining functions (if this makes it easier/simpler).
BTW it's running 1.3.2 jQuery
Example: (not working)
http://jsfiddle.net/NYn8e/1/
Any suggestions?
JS:
function checkboxSelectedRequiredAdditionalFields(elem) {
var passedElement = $('input:checkbox[name=' + elem + ']');
passedElement.click(function() {
$('input[name=number]').attr('required', true).append('<span class="required">*</span>');
alert('text is required now?');
});
}
function numberEnteredRequiredAdditionalFields(elem) {
var passedElement = $('input[name=' + elem + ']');
if (passedElement.val().length > 0) {
var boxes = $('input[data-group=cbOptions]').click(function() {
boxes.not(this).attr('required', false);
alert('checkbox is selected so other checkbox is not required');
});
$('input[data-group=cbOptions]').each(function() {
$(this).attr('required', true).next().append('<span class="required">*</span>');
alert('checkbox is required now?');
});
}
}
HTML
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox1');" data-group="cbOptions">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox2');" data-group="cbOptions">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" onclick="numberEnteredRequiredAdditionalFields('number');">
</b>
</form>
You should separate the JavaScript from the HTML. Fiddle: http://jsfiddle.net/NYn8e/6/. If possible, remove <b> from the HTML source, and extend the style sheet with the right CSS property: font-weight: bold;.
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" data-required="checkbox">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" data-required="checkbox">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" data-required="number">
</b>
</form>
JavaScript:
function required(){
//Any checked checkbox? checked == 0 = no, otherwise: yes
var checked = $('input[data-required=checkbox]:checked').length;
var $checkboxes = $('input[data-required=checkbox]');
var $num = $('input[name=number]');
var length = $num.val().length;
//Remove previously added span, if existent.
$num.next('span.required').remove();
$checkboxes.next('span.required').remove();
if(!length && checked){
$num.after('<span class="required">*</span>');
alert("Number required!");
} else if(length && !checked){
$checkboxes.after('<span class="required">*</span>');
alert("Check at least one checkbox.");
}
}
$(document).ready(function(){
$("[data-required]").change(required);
});
=) Would this one help you?
<form id='myForm'>
<input type='checkbox' name='checkbox1' value='t' id='checkbox1' onchange='alertUser()' />
<input type='checkbox' name='checkbox2' value='t' id='checkbox2' onchange='alertUser()' />
<input type='text' name='number' id='number' onchange='alertUser()'/>
</form>
<script type='text/javascrip>
function alertUser() {
var checked1 = $('#checkbox1').attr('checked');
var checked2 = $('#checkbox2').attr('checked');
var number = $('#number').val();
if ((checked1 == true || checked2 == true) && number == '') {
alert('Number is required!');
} else if (number != '' && (checked1 != true && checked2 != true)) {
alert('One of the checkbox need to be checked!');
}
});
</script>
This should hopefully give you an idea on how to accomplish the task. http://jsfiddle.net/NYn8e/8/
var $textbox = $('input[name=number]').hide();
$('input[type=checkbox]').change(function() {
var $this = $(this); //store jquery object
//get the other checkbox
var $other= ($this.attr('name') === 'checkbox1') ? $('input[name=checkbox2]') : $('input[name=checkbox1]');
if (!$other.is(':checked') && !$this.is(':checked')) {
$textbox.val('').hide();
} else{
$textbox.show();
}
});

Categories

Resources