Javascript and HTML - onclick - javascript

Suppose I have the following code which creates two radio buttons:
<li id="foli517" class=" ">
<label class="desc" id="shippingChoice" for="Field517_0">
Shipping Options
</label>
<div>
<input id="shippingChoice" name="Field517" type="hidden" value="" />
<span>
<input id="shipping1" name="Field517" type="radio" class="field radio" value="$2.00 Shipping Fee" tabindex="13" checked="checked" />
<label class="choice" for="Field517_0" >
$2.00 Shipping Fee</label>
</span>
<span>
<input id="Field517_1" name="Field517" type="radio" class="field radio" value="I will pick up the items (free shipping)" tabindex="14" />
<label class="choice" for="Field517_1" >
I will pick up the items (free shipping)</label>
</span>
</div>
</li>
How would I implement a javascript function onclick which updates the inner html of a span with id "mySpan" with the word "FREE" when the 2nd radio button is clicked, and "NOT FREE" otherwise?
document.getElementById(WHAT GOES HERE).onclick = function() {
//what goes here?
};

document.getElementById('foli517').onchange = function(e) {
var e = e || event;
var target = e.target || e.srcElement;
var span = document.getElementById('mySpan');
var span2 = document.getElementById('mySpan2');
if (target.type === "radio") {
span.innerHTML = (target.id === "Field517_1") ? "FREE" : "NOT FREE";
}
if (target.type === "checkbox") {
span2.innerHTML = "Is it checked? " + target.checked;
}
};
Example: http://jsfiddle.net/pEYnm/2/

I would add onclick="setSpan('FREE');" and onclick="setSpan('NOT FREE');" to HTML of the respective radio buttons then add a javascript function as below that sets the HTML of the span.
function setSpan(text) {
document.getElementById('mySpan').innerHTML = text;
}

Please check Working code of Radio button on click !

Related

Condition: input:checked with the same class

I would like to have a little help on an enigma that I have.
I have a button that changes according to the number of input:checked
but I would like to add a condition which is: select of the checkboxes of the same class.
for example can I have 2 or more input.
<input class="banana" type="checkbox" value="Cavendish">
<input class="banana" type="checkbox" value="Goldfinger">
<input class="chocolato" type="checkbox" value="cocoa powder">
<input class="chocolato" type="checkbox" value="milk chocolate">
<input class="apple" type="checkbox" value="honneycrisp">
<input class="apple" type="checkbox" value="granny smith">
I can't use attribute name or value. it is not possible to modify the inputs.
the condition:
$('input[type="checkbox"]').click(function(){
if($('input[type="checkbox"]:checked').length >=2){
////////
if (my classes are the same) {
$('#btn').html("click me").prop('disabled', false);
} else {
$('#btn').html("too bad").prop('disabled', true);
}
//////
}
I try with
var checkClass = [];
$.each($("input[type="checkbox"]:checked"), function() {
checkClass.push($(this).attr('class'));
});
I don't know if I'm going the right way or if I'm complicating the code but a little help would be welcome. For the moment my attempts have been unsuccessful.
The following function will reference the first checkbox that's checked className and enable each checkbox that has said className whilst disabling all other checkboxes. Details are commented in Snippet.
// All checkboxes
const all = $(':checkbox');
// Any change event on any checkbox run function `matchCategory`
all.on('change', matchCategory);
function matchCategory() {
// All checked checkboxes
const checked = $(':checkbox:checked');
let category;
// if there is at least one checkbox checked...
if (checked.length > 0) {
// ...enable (.btn)...
$('.btn').removeClass('off');
// ...get the class of the first checked checkbox...
category = checked[0].className;
// ...disable ALL checkboxes...
all.attr('disabled', true);
// ...go through each checkbox...
all.each(function() {
// if THIS checkbox has the class defined as (category)...
if ($(this).is('.' + category)) {
// ...enable it
$(this).attr('disabled', false);
// Otherwise...
} else {
// ...disable and uncheck it
$(this).attr('disabled', true).prop('checked', false);
}
});
// Otherwise...
} else {
// ...enable ALL checkboxes...
all.attr('disabled', false);
// ...disable (.btn)
$('.btn').addClass('off');
}
return false;
}
.off {
pointer-events: none;
opacity: 0.4;
}
<input class="beverage" type="checkbox" value="Alcohol">
<label>🍸</label><br>
<input class="beverage" type="checkbox" value="Coffee">
<label>☕</label><br>
<input class="dessert" type="checkbox" value="cake">
<label>🍰</label><br>
<input class="dessert" type="checkbox" value="Ice Cream">
<label>🍨</label><br>
<input class="appetizer" type="checkbox" value="Salad">
<label>🥗</label><br>
<input class="appetizer" type="checkbox" value="Bread">
<label>🥖</label><br>
<button class='btn off' type='button '>Order</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
some thing like that ?
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
var checked_class = ''
;
bt_restart.onclick = _ =>
{
checked_class = ''
chkbx_all.forEach(cbx=>
{
cbx.checked=cbx.disabled=false
cbx.closest('label').style = ''
})
}
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
if (checked_class === '') checked_class = cbx.className
else if (checked_class != cbx.className )
{
cbx.checked = false
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input class="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input class="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input class="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input class="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input class="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input class="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>
In fact it's like a Matching Pairs card game
this answer is without global checked_group variable, and respecting epascarello message about data attribute see also usage.
Adding a repentance on uncheck elements
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
function clearGame()
{
chkbx_all.forEach(cbx=>
{
cbx.checked = cbx.disabled = false
cbx.closest('label').style = ''
})
}
bt_restart.onclick = clearGame
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
let checkedList = document.querySelectorAll('input[type=checkbox]:checked')
if (cbx.checked)
{
let checked_group = ''
checkedList.forEach(cEl=>{ if (cEl !== cbx) checked_group = cEl.dataset.group })
if (checked_group === '') checked_group = cbx.dataset.group
else if (checked_group !== cbx.dataset.group )
{
cbx.checked = false // you need to uncheck wrong group checkboxes for preserving checkedList
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
else if (checkedList.length === 0) // case of cheked repentir
clearGame()
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input data-group="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input data-group="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input data-group="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input data-group="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>

I want to catch all labels of checked checkbox in javascript

Is there a way to catch all the label texts of a checked checkbox in Javascript (not JQuery).
My HTML is:
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
I want to catch the label of the checked checkbox in Javascript in order to use it as Javascript Variable in Google Tagmanager.
Currently I've got this code (from www.simoahava.com) to catch the values of the checked checkboxes.
function () {
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-containter input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(inputs[i].value);
}
}
return selectedCheckboxes;
}
This script gives me all the values, but these are none-descriptive values. But I want the descriptive labels.
Is there a way to catch the text within the span with class .wpgu-onboarding-answer-title of all checked checkboxes ?
Thanks in Advance
Erik.
Apart from the previous solution, would like to share one more simple solution based on the code mentioned in the question. The solution can be as simple as fetching all the labels with class as wpgu-onboarding-answer-title and based on which input element is selected, fetch the respective label index and use it.
Please note that I have added an extra button for testing the function easily.
function abc() {
var labels = document.querySelectorAll('.wpgu-onboarding-answer-title');
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-container input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(labels[i].textContent);
//selectedCheckboxes.push(inputs[i].value);
}
}
console.log(selectedCheckboxes);
return selectedCheckboxes;
}
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
<button onclick="abc()">
Fetch All Chkbox Values
</button>
Please note that this solution would only work if you have wpgu-onboarding-answer-title class being used for only this purpose and not anywhere else in the page before.
Based on this answer using jQuery, you can use an attribute selector and the ID of the element you want to get the label for, e.g. document.querySelector('label[for=' + button.id + ']'), then get its textContent to get the actual label:
document.querySelectorAll('input.wpgu-onboarding-answer-checkbox').forEach(input => {
console.log(input.id + ' ' +
document.querySelector('label[for=' + input.id + ']').textContent.trim() + ' ' +
(input.checked? '' : 'not ') + 'checked'
)
});
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
This could help you.
var inputs = document.querySelectorAll(".wpgu-onboarding-answer-container input:checked+label>span");
var checkbox = [];
inputs.forEach(input=>{
checkbox.push(input.textContent);
console.log(input.textContent)
});
Good lucky!

How can I change the maxlength validation for a text input based on a radio button selection?

I have three radio buttons on my page, and a text input:
<div class="row-fluid" style="padding-bottom: 5px;">
<label class="radio inline"><input type="radio" name="optionsRadios" id="optionsRadios1" value="Name" checked>Search By Name </label>
<label class="radio inline"><input type="radio" name="optionsRadios" id="optionsRadios2" value="City">Search By City </label>
<label class="radio inline"><input type="radio" name="optionsRadios" id="optionsRadios3" value="Code">Search By code </label>
</div>
<div class="row-fluid">
<span class="row-fluid">
<input type="text" id="txtSearch" name="txtSearch" />
<input type="button" id="btnSubmit" value="Search" class="btn btn-primary" />
</span>
</div>
I'm trying to validate the length of the input on txtSearch based on the selected radio button, as the database fields are different lengths for those columns:
Updated:
$("#frmSearch").validate({
debug: false,
rules: {
'txtSearch': {
required: true,
maxlength: function () {
var sel = $('input[name=optionsRadios]:checked', '#frmSearch').val();
if (sel == 'City') {
return 25;
}
else {
return 50;
}
},
minlength: 2
}
}
});
I put the alerts in to tell me the lengths of the values, and all the alerts return what I expect, but the validation message displayed on every entry, no matter the length, is "Please enter no more than 1 characters."
Delete the depends and replace with this:
maxlength: (function(){
var sel = $('input[name=optionsRadios]:checked', '#frmOfficeSearch').val();
if (sel == 'Name') {
return 50;
}
if (sel == 'City') {
return 25;
}
if (sel == 'Code') {
return 50;
}
})()
This creates a self executing function that returns the correct integer based on the selected radio.

Validating if the radio button group is selected JQUERY

I'm trying to validate the radio button group,. if not check the span will have a text which indicates that the radio button must be selected,. the problem is,. if I place the codes of radion button validation on top, it does not work, but when it is below,. it works.. Kinda weird,. any idea for this one? thanks
$("#mchoice").submit(function () {
var direction = $('#direction').val();
var quiztxtBox = document.getElementsByName('quiztxtBox[]');
var isSubmit;
var names = [];
var err = document.getElementsByName('errMchoice[]');
// For radio button answers.
$('input[type="radio"]').each(function(){
names[$(this).attr('name')] = true;
});
if (!direction)
{
$('#direction').focus();
$('#direction').css({"background-color":"#f6d9d4"});
$('#direction').nextAll('span').html('Type in direction.');
event.preventDefault();
}
else
{
$('#direction').css({"background-color":"#fff"});
$('#direction').nextAll('span').html("");
}
for(correct_answer in names)
{
var radio_buttons = $("input[name='" + correct_answer + "']");
if( radio_buttons.filter(':checked').length == 0)
{
radio_buttons.nextAll('span').html('Select the answer.');
event.preventDefault();
}
else
{
radio_buttons.nextAll('span').html('');
}
}
// Choices fields
$("[name='quiztxtBox[]']").each(function(){
if (!this.value.length)
{
$(this).css({"background-color":"#f6d9d4"}).siblings('span.errorMsg').text('Please type in question/answer!');
event.preventDefault();
}
else
{
$(this).css({"background-color":"#fff"}).siblings('span.errorMsg').text("");
}
});
});
HTML here
<div id="QuestionTBDiv1" >
<label>Question</label><br/>
<input type="text" name="quiztxtBox[]" size="57" id="quiztxtBox[]" placeholder="Question #1"><br/>
<label>Answer</label><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A"> <input type="radio" class = "choiceA" name="correct_answer1" value="A">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice B"> <input type="radio" class = "choiceB" name="correct_answer1" value="B"><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice C"> <input type="radio" class = "choiceC" name="correct_answer1" value="C">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice D"> <input type="radio" class = "choiceD" name="correct_answer1" value="D"><br>
<span name="errMchoice" class="errorMsg"></span>
</div>
JsFiddle:http://jsfiddle.net/Ej77L/2/
There was a small logical error in your javascript.
Once you set the span with error message of 'Select an answer' you are doing a checking if the question has been filled. If it has been filled then you are making the span text empty.
So instead of that, keep a flag to see if the answer was selected or not. If not selected then set the flag and in later part of the code, don't empty span text
Here's a working DEMO

jquery click event resets check property of checkbox

I have a checkboxlist control, in this control I wan't every checkbox to fire an event whenever the checkbox is clicked (manually or programmatically).
Html code generated by checkboxlist lloks something like below:
<div id="divleft">
<table id="MainContent_CheckBoxList1">
<tbody>
<tr>
<td><input id="MainContent_CheckBoxList1_0" name="ctl00$MainContent$CheckBoxList1$0" onclick="router(this);" value="1" type="checkbox"><label for="MainContent_CheckBoxList1_0">Option1</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_1" name="ctl00$MainContent$CheckBoxList1$1" onclick="router(this);" value="2" type="checkbox"><label for="MainContent_CheckBoxList1_1">Option2</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_2" name="ctl00$MainContent$CheckBoxList1$2" onclick="router(this);" value="3" type="checkbox"><label for="MainContent_CheckBoxList1_2">Option3</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_3" name="ctl00$MainContent$CheckBoxList1$3" onclick="router(this);" value="4" type="checkbox"><label for="MainContent_CheckBoxList1_3">Option4</label></td>
</tr>
</tbody>
</table>
</div>
On click of checkbox I am hiding or showing div(s). The div looks like:
<div id="divright">
<div id="divoption1" style="display: none;">
I am in option1 div
</div>
<div id="divoption2" style="display: none;">
I am in option2 div
</div>
<div id="divoption3" style="display: none;">
I am in option3 div
</div>
</div>
</div>
I have a jquery code which does the heavy duty work for showing / hiding divs.
$(document).ready(function () {
RunOnce();
});
function uncheckAllCheckboxes(previouscheckedCheckboxValue, currentcheckedCheckboxValue) {
if (previouscheckedCheckboxValue != null && previouscheckedCheckboxValue != currentcheckedCheckboxValue) {
window.isRunOnce = 'false';
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
//variable used to avoid infinite loop
window.isRunOnce = null;
}
return currentcheckedCheckboxValue;
}
function router(control) {
if (control.value == '1') {
Option1Controller(control.value);
}
if (control.value == '2') {
Option2Controller(control.value);
}
if (control.value == '3') {
Option3Controller(control.value);
}
}
function Option1Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption1]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption1]').hide();
}
}
function Option2Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption2]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption2]').hide();
}
}
function Option3Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption3]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption3]').hide();
}
}
function RunOnce() {
Option1Controller('1');
Option2Controller('2');
Option3Controller('3');
}
Problem lies with function uncheckAllCheckboxes, in this function, I am unchecking previously checked checkboxes:
I have tried:
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false);
Above query unchecks the corresponding checkbox but does not fire the onclick event?
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').click(); just after the above query.
It fires the click event but also undoes 1, so it is useless.
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
This query also seems to do nothing
My requirement is simple: I need to pro grammatically check/uncheck checkboxes which are identified by parent id and the value of checkbox control. After checking/unchecking, the control should fire click event also.
Any help shall be appriciated.
Note: I am new to this jquery stuff, so any improvements in my code are also welcomed.
Have you considered using radio buttons instead of checkboxes? They have same behavior you trying to achieve with checkboxes. I've created a fiddle
HTML
<label for="checkbox1">Div 1</label>
<input type="checkbox" name="div" id="checkbox1" data-div-id="1">
<label for="checkbox2">Div 2</label>
<input type="checkbox" name="div" id="checkbox2" data-div-id="2">
<label for="checkbox3">Div 3</label>
<input type="checkbox" name="div" id="checkbox3" data-div-id="3">
<hr/>
<div id="div1">DIV1</div>
<div id="div2">DIV2</div>
<div id="div3">DIV3</div>
<br/>
<label for="radio1">Div 4</label>
<input type="radio" name="div" id="radio1" data-div-id="4">
<label for="radio2">Div 5</label>
<input type="radio" name="div" id="radio2" data-div-id="5">
<label for="radio3">Div 6</label>
<input type="radio" name="div" id="radio3" data-div-id="6">
<hr/>
<div id="div4">DIV4</div>
<div id="div5">DIV5</div>
<div id="div6">DIV6</div>
JS
$(document).ready(function() {
var checkboxes = $('input:checkbox'),
radios = $('input:radio'),
divs = $('div');
// hide all divs
divs.hide();
checkboxes.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
$('#div' + $(target).data('div-id')).toggle();
});
radios.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
divs.hide();
$('#div' + $(target).data('div-id')).toggle();
});
});
you can see the comparison between both. And wouldn't use inline js anymore and css when possible. And try to avoid using tables if it not for tabular data, they are known for causing performance issues. Read this
I think you are using too much code.
Check this:
$('input[type="checkbox"]').change(function () {
var this_index = $(this).closest('tr').index(); //check the index of the tr of this input
$("#divright > div").eq(this_index).show(); //show the div inside divright that has same index as this_index
});
And this demo. I removed all inline function calls. I think this is a easier way.

Categories