condition if two checkboxes are checked doesn't work in jquery - javascript

I have two radio groups. I wish to put a condition where if pRange is checked (val=pRange) and periodType value is 'one', 'two' or 'three', it displays a div called message. but my js code below doesn't seem to work. Any help is much appreciated.
$("input[name$='periodType']").change(function() {
var grpname = $(this).val();
var pname = $("input:radio[name='mainPeriod']:checked").val();
if (((grpname == "one") || (grpname == "two") || (grpname == "three")) && (pname=="pRange")) {
alert( pname + ' gname= ' + 'yes'); $('.message').show;
}
else {
alert( pname + ' gname= ' + 'no');
}
});
GROUP 1
<input type="radio" name="mainPeriod" id="pRange" val="pRange" />
<input type="radio" name="mainPeriod" id="pHour" val="pHour" />
<input type="radio" name="mainPeriod" id="pDay" val="pDay" />
<input type="radio" name="mainPeriod" id="pWeek" val="pWeek" />
<input type="radio" name="mainPeriod" id="pMonth" val="pMonth" />
GROUP 2
<input type="radio" name="periodType" val="one" />
<input type="radio" name="periodType" val="two" />
<input type="radio" name="periodType" val="three" />
<input type="radio" name="periodType" val="four" />
<input type="radio" name="periodType" val="five" />
<div class="message" style="display:none;">Message</div>

Whipped up a quick fiddle jsfiddle
your radio values are written as val="" not value="" don't know if that was just for the test or in your actual code.

I checked the console of your values
var grpname = $(this).val();
var pname = $("input:radio[name='mainPeriod']:checked").val();
The both return on/off only which is causing the issue. What you need to get is the .attr('val') so you can check the values
var grpname = $(this).attr('val');
var pname = $("input:radio[name='mainPeriod']:checked").attr('val');
Here's a fiddle http://jsfiddle.net/B9GyV/

Related

Find all duplicate ids and add unique key

how to find all duplicate ids when the page is relaod:
Let's say we have html like this:
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
The idea is to find duplicate ids and add +1 or something like that:
What I want to achieve is:
<input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />
JS
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
$(this).attr('id', $(this).attr('id') + i);
});
Any ideas? Thank you all.
I would strongly recommend you serve valid HTML rather than manipulating Ids.
However, You are were close as attribute value selector may return multiple elements, You need to iterate the matching elements
var handled = [];
$('[id]').each(function() {
if (handled.includes(this.id)) {
return;
}
var elemets = $('[id="' + this.id + '"]');
if (elemets.length > 1) {
handled.push(elemets.attr('id'));
elemets.attr('id', function(index, v) {
return v + (index+1);
});
}
});
//For Readablity
$('[id]').each(function(){
console.log(this.outerHTML)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
Try like this.
var allId = [];
var data = [];
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(allId.indexOf(this.id) < 0){
data[this.id] = 1;
allId.push(this.id);
} else {
data[this.id]++;
}
$(this).attr('id', $(this).attr('id') + data[this.id]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
No need for jQuery:
const ids = {}
document.querySelectorAll('[id]').forEach(node => {
if (ids[node.id] !== undefined) {
ids[node.id] += 1
} else {
ids[node.id] = 1
}
node.id = `${node.id}${ids[node.id]}`
})
document.querySelectorAll('[id]').forEach(node => console.log(node))
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
try this
var i = 0;
('[id]').each(function(){
var allIds = $('[id^="'+this.id+'"]').length
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
var i = allIds - ids.length + 1
$(this).attr('id', $(this).attr('id') + i++);
})
var a = [];
var i =0;
jQuery('[id]').each(function(){
if(a.indexOf(this.id) !== -1){ //checks if id exists in array
i++;
}
else{
i = 1;
a.push(this.id);
}
jQuery(this).attr('id', jQuery(this).attr('id') + i);
});
Explaination : I am storing each new id in array. At each iteration it checks whether the id is repeated, if so then the attribute is incremented to 1.

How to make one of three inputs type button requierd required

My problem is that I have one form with some fields and three inputs type button, they all represents one message. I want to make chooseing one of three messages required. My code is bellow:
<input id="poruka1" type="button" class="hm_datumibtn poruka" name="poruka1" value="Pored mene, sve želje " >
<input id="poruka2" type="button" class="hm_datumibtn poruka" name="poruka2" value="Pored sebe, sve želje " >
<input id="poruka3" type="button" class="hm_datumibtn poruka" name="poruka3" value="Pored tebe, sve želje " >
Do you have any idea how can I solve this kind of problem?
<script>
function upis(){
//var datum = $(this).find('.datum').val();
//var poruka = $(this).find('.poruka').val();
//var poruka = $(this).attr('value');
if (poruka_forma.poruka1.value == '' && poruka_forma.poruka2.value == ''&& poruka_forma.poruka3.value == '') {
alert('You have to choose message.');
return false;
}
else {
myForm.submit();
}
var ime = document.getElementById("ime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var elementsdate = document.getElementsByClassName("selected_date");
var datum = elementsdate[0].value;
var elements = document.getElementsByClassName("selected");
var poruka = elements[0].value;
//var poruka = document.getElementById("poruka").value;
//var datum = document.getElementById("datum").value;
//var poruka = document.getElementById("poruka").value;
//var email = document.getElementById("email").value;
//var dataString = "ime="+encodeURIComponent(ime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
//data: dataString+'&datum='+datum+'&poruka='+poruka,
data: {ime:ime,ime_slavljenik:ime_slavljenik,datum:datum, poruka:poruka},
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
I think you might want to use <input type="radio" /> instead. Example:
<form>
<input type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>
You can add required attributes to make them required. Also, adding checked attributes will make a radio button selected by default.
You can also use <label> with for attribute. When that label is clicked, it selects a radio button that it refers to by id in its for attribute.
Edit: I saw your comment that you don't want to use radio buttons because of the design. You can actually hide the radio buttons, and just use <label> with for attributes. Example:
<style>
#radio_btn_1:checked + label{background-color:red;}
#radio_btn_2:checked + label{background-color:red;}
#radio_btn_3:checked + label{background-color:red;}
</style>
<form>
<input style="display:none;" type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input style="display:none;" type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input style="display:none;" type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>

How to Validate Multiple radio buttons

How can I validate multiple radio buttons. All these radio buttons generated dynamically.
<input type="radio" name="answer_option1" value="1" id="ans_options1" />
<input type="radio" name="answer_option1" value="2" id="ans_options2" />
<input type="radio" name="answer_option1" value="3" id="ans_options3" />
<input type="radio" name="answer_option1" value="4" id="ans_options4" />
<input type="radio" name="answer_option2" value="5" id="ans_options5" />
<input type="radio" name="answer_option2" value="6" id="ans_options6" />
<input type="radio" name="answer_option2" value="7" id="ans_options7" />
<input type="radio" name="answer_option2" value="8" id="ans_options8" />
<input type="radio" name="answer_option3" value="9" id="ans_options9" />
<input type="radio" name="answer_option3" value="10" id="ans_options10" />
<input type="radio" name="answer_option3" value="11" id="ans_options11" />
<input type="radio" name="answer_option3" value="12" id="ans_options12" />
<input type="radio" name="answer_option4" value="13" id="ans_options13" />
<input type="radio" name="answer_option4" value="14" id="ans_options14" />
<input type="radio" name="answer_option4" value="15" id="ans_options15" />
<input type="radio" name="answer_option4" value="16" id="ans_options16" />
Try this http://jsfiddle.net/aamir/r9qR2/
Since each group has different name attribute so you have to do validation for each set of radio buttons.
if($('input[name="answer_option1"]:checked').length === 0) {
alert('Please select one option');
}
If you have unlimited number of groups. Try this http://jsfiddle.net/aamir/r9qR2/2/
//Make groups
var names = []
$('input:radio').each(function () {
var rname = $(this).attr('name');
if ($.inArray(rname, names) === -1) names.push(rname);
});
//do validation for each group
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length === 0) {
console.log('Please check ' + name);
}
});
If you want to show just 1 error for all groups. Try this http://jsfiddle.net/aamir/r9qR2/224/
try this new fiddle http://jsfiddle.net/Hgpa9/3/
$(document).on("click","#validate", function() {
var names = [];
$('input[type="radio"]').each(function() {
// Creates an array with the names of all the different checkbox group.
names[$(this).attr('name')] = true;
});
// Goes through all the names and make sure there's at least one checked.
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if (radio_buttons.filter(':checked').length == 0) {
alert('none checked in ' + name);
}
else {
// If you need to use the result you can do so without
// another (costly) jQuery selector call:
var val = radio_buttons.val();
}
}
});
var names = []
$('input[name^="answer_option"]').each(function() {
var rname = $(this).attr('name');
if ($.inArray(rname, names) == -1) names.push(rname);
});
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length == 0) {
console.log('Please check ' + name);
}
});

how to read if radio button checked and save it as 1 with javascript?

I have 3 radio buttons:
<div id="step-1">
<h2 class="StepTitle">
<label style="font-weight: bold; color: #662819;" id="frage1"></label>
</h2>
<br />
<input type="radio" name="group1" id="antwort1" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />
<label id="antwort1fuerFrage1"></label>
<br />
<br />
<input type="radio" name="group1" id="antwort2" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />
<label id="antwort2fuerFrage1"></label>
<br />
<br />
<input type="radio" name="group1" id="antwort3" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />
<label id="antwort3fuerFrage1"></label>
</div>
I am trying to read if radio button is checked, and save a value (need 1 or/ 0) like this:
var frage1 = document.getElementById("frage1").innerHTML;
var antwort1 = document.getElementById("antwort1");
var antwort2 = document.getElementById("antwort2");
var antwort3 = document.getElementById("antwort3");
antwort1 = $('input[id="antwort1"]:checked').val();
antwort2 = $('input[id="antwort2"]:checked').val();
antwort3 = $('input[id="antwort3"]:checked').val();
antwort 1, 2, 3 are undefined. I need to get 0 or 1.
You could just use .length since you're querying IDs:
antwort1 = $('#antwort1:checked').length;
antwort2 = $('#antwort2:checked').length;
antwort3 = $('#antwort3:checked').length;
Use prop() like
antwort1 = $('input[id="antwort1"]').prop();
antwort2 = $('input[id="antwort2"]').prop();
antwort3 = $('input[id="antwort3"]').prop();
Fiddle
You could do like this:
var antwort1 = $('#antwort1:checked').length;
var antwort2 = $('#antwort2:checked').length;
console.log(antwort1);
console.log(antwort2);
FIDDLE DEMO

jQuery: Verify If one of multiple required checkboxes is/are checked

I have a form with multiple groups of checkboxes (among other things). Some of these groups are mandatory fields (At least one checkbox needs to be checked within that group).
I am able to tell if a group has a checkbox checked, but I failed to make them mandatory. Also I am need to get one long string with the values of the selected checkbox(es). I would need to have a string where if the user checks, say the first 3 checkboxes from group1, the string to be:
"zero | 1 val | 2 val"
The code is a simplified version of my original. Here is the jFiddle: http://jsfiddle.net/QyY2P/1/
Also, for your convenience I am also including the code here:
jQuery:
function countChecked() {
//Group 1
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});
//Group 2
var n = $("#group2 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group2 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection3").text(txt);
alert($(this).val() + " | ");
});
}
countChecked();
$(":checkbox").click(countChecked);
HTML:
<form>
<div id="group1">
<p> *Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 val" />
<input type="checkbox" name="ckb_unit[]" value="2 val" />
<input type="checkbox" name="ckb_unit[]" value="3 val" />
<input type="checkbox" name="ckb_unit[]" value="4 val" />
</div>
<div id="group2">
<p>Please select a box</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="A" />
<input type="checkbox" name="ckb_unit[]" value="B" />
<input type="checkbox" name="ckb_unit[]" value="C" />
<input type="checkbox" name="ckb_unit[]" value="D" />
</div>
<div id="group3">
<p>*Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 A" />
<input type="checkbox" name="ckb_unit[]" value="2 B" />
<input type="checkbox" name="ckb_unit[]" value="3 C" />
<input type="checkbox" name="ckb_unit[]" value="4 D" />
</div>
</form>
<!-- For debugging purposes -->
<br/>
<div id="count"></div>
<div id="selection1"></div>
<div id="selection3"></div>
PS. I am a beginner, perhaps you noticed it by my not so elegant coding >_<
You can make it mandatory by checking if n is 0 when the user hits submit and then attracting the user's attention towards it somehow (appending an error message, for example). I'm talking about this n:
var n = $("#group1 input:checked").length;
Looking at JSFiddle, it seems you didn't declare txt as a variable, so this works for me:
//Group 1
var txt = ""; // initialise txt with an empty string, so you can append to it later
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});

Categories

Resources