HTML
<input type="checkbox" value="One" checked="checked" id="r1" name="g" />
<label for="r1">
One
</label>
<input type="checkbox" value="Two" id="r2" name="g" />
<label for="r2">
Two
</label>
<input type="button" value="Status" onclick="MyFunction()" />
Javascript
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked == true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextSibling.innerHTML);
}
}
}
Here I am getting the Index of the checkboxes which are checked.
How to get the text of the selected Checkboxes?
Demo:http://jsfiddle.net/u95uN/
Thanks for ur help.
Because in many browsers, the nextSibling will be an empty text node.
USE nextElementSibling instead of nextSibling
WORKING DEMO
The ChildNode.nextElementSibling read-only property returns the
element immediately following the specified one in its parent's
children list, or null if the specified element is the last one in the
list.
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked === true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextElementSibling.innerHTML);
}
}
}
MyFunction();
Since you tagged this with jQuery I'll answer using jQuery.
Here's the fiddle: http://jsfiddle.net/5xL56/3/
Explanation:
On button click:
$("#btn").click
It will run through every checkbox with the name "g":
$("input[type=checkbox][name=g]").each
Try this, You are writing JavaScript on load, mention in head or body as below:
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked === true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextElementSibling.innerText);
}
}
}
Demo
Use chk[i].value to fetch the value of the checked checkbox.
alert("Text at index " + i + chk[i].value);
Demo
Please correct this line !
alert("Text at index " + i + chk[i].nextSibling.nextSibling.innerText);
Or you can use;
alert("Text at index " + i + chk[i].nextElementSibling.innerText);
Or you can use; (My way)
alert("Text at index " + i + chk[i].value);
To see this options, you can write in javascript your code "console.log(chk[i])" than you can see your options to get the text.
Try this I think this would work :
$.each($("input[name='g']:checked"),function(i,element){
var id = $(element).attr("id");
var text = $("label[for='"+id+"']").text();
alert(text);
});
Use nextElementSibling instead of nextSibling
Fiddle demo
nextSibling checks for whatever there is following the current element and hence even line-break or space etc are also considered even if these are not HTML elements and nextSibling() is only for that.
But nextElementSibling searches for the next HTML element that here is the <label> and hence it is what you need.
Related
I have a dynamic input field that gets appended after a plus button.
The corresponding id of these fields are answer0, answer1, answer2 and so on. That means after button click the id will be dynamically appended to the text field.
Now I want to validate these fields. My validation code is as follows
function showValidation(response) {
var respArray = JSON.parse(response.responseText).errors;
for(var i=0;i<=(Object.keys(respArray).length);i++){
var optionss= 'Enter Answers.';
if($("#answer"+i).val()==''){
$('#answer'+i+' + span').html('');
$('#answer'+i).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>');
$('#answer'+i).focus();
}
}
}
I am checking till response error length. But before giving values in these fields, validation works properly(fig 1). But if I enter values for first 2 fields as in the image above, the validation message does not shows for the third field (fig 2). Because at this stage the id is answer2 and the loop 'i' value checks 0 first and next checks 1. So inside loop answer0 and answer1 are having values so the validation stops there. I need to get validation for the next fields too. Thanks in advance.
My HTML and corresponding append function
<input class="form-control" name="answer0[]" id="answer0" placeholder="OPTION 1">
<a class="add-option" onclick="AppendOption()"><img src="{{asset('admin/images/icn-add-option.png')}}" alt=""></a>
function AppendOption(){
var k=1;
$('#appendOption').append('<div class="form-group row"><div class="col-md-4"><input class="form-control" name="answer0[]" id="answer'+k+'" placeholder="OPTION" ></div></div>');
k++;
}
In your AppendOption function, you set k=1 This is an invalid option once you reach the third entry (option 2). You should instead detect that, better yet still make it context sensitive when it executes. I did this by adding a answer-item class and detecting how many we have and using that number instead.
I wrapped all this in a <div id="options-container"> so I would have a place to hook the event handler (delegateTarget) https://api.jquery.com/event.delegateTarget/
I would not have used an ID here and instead used classes, but that is not part of the question but more rather the cause of it.
$('.options-container').on('click','.add-option',function(event){
let k= $(event.delegateTarget).find('.answer-item').length;
$(event.delegateTarget).append('<div class="form-group row"><div class="col-md-4"><input class="form-control answer-item" name="answer0[]" id="answer' + k + '" placeholder="OPTION" ></div></div>');
});
function showValidation(response) {
var respArray = JSON.parse(response.responseText).errors;
for (var i = 0; i <= (Object.keys(respArray).length); i++) {
var optionss = 'Enter Answers.';
if ($("#answer" + i).val() == '') {
$('#answer' + i + ' + span').html('');
$('#answer' + i).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss + '</span>');
$('#answer' + i).focus();
}
}
}
<div id="options-container">
<input class="form-control answer-item" name="answer0[]" id="answer0" placeholder="OPTION 1">
<a class="add-option"><img src="{{asset('admin/images/icn-add-option.png')}}" alt=""></a>
</div>
If the fields are required you should mark them as required otherwise you validate every field. In your case another way for validating could look like this
function showValidation(response) {
var respArray = JSON.parse(response.responseText).errors;
$('.form-group input.form-control').each(function(){
if ($(this).val() == '') {
$(this).next('span').html('');
$(this).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>');
$(this).focus();
}
});
}
Since I don't know how and where the showValidation() is called I can't improve it further.
I tried to display the error messages inside an input array loop and I got the answer.
var result = document.getElementsByTagName("input");
var optionss= 'Enter Answers.';
for (var j = 0; j < result.length; j++) {
if($("#answer"+j).val()==''){
$('#answer'+j+' + span').html('');
$('#answer'+j).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>');
$('#answer'+j).focus();
}
I have a whole bunch of radio buttons formatted in the following way;
<input type="radio" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
and my incrementIndex() function is simple enough;
var index = 0;
function incrementIndex() {
index += 1;
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
}
And when a radiobutton is clicked it increments the index, but I want it to increase the index once and only if the button is not checked, the way it is set up, even if the Xch radio button is checked, it keeps increment the index! Please help.
Not sure why you would want to do something like this, but is this what you were trying to do?
<input type="radio" name="ch" value="XCheese " onclick="incrementIndex(this)">XCheese</input><br>
<input type="radio" name="ch" value="YCheese " onclick="incrementIndex(this)">YCheese</input><br>
<input type="radio" name="ch" value="ZCheese " onclick="incrementIndex(this)">ZCheese</input><br>
var index = 0;
var previousValue;
function incrementIndex(e)
{
if(e.checked && e != previousValue) index += 1;
previousValue = e;
alert(index);
}
Here's an example
http://jsfiddle.net/Md8fj/134/
What you're doing isn't exactly clear, but if you want the desired behavior, move the index += 1 inside the if statement that detects if it's already checked. If it's not, then you can increment.
Something like:
var index = 0;
function incrementIndex() {
document.getElementById("demo").innerHTML = ""+index+"";
if ($("#Xch").attr("checked") == true){
index = 10;
}
else {
index += 1;
}
}
You need to use a checkbox instead of a radiobox.
In a radio group, once an input is selected, one input in the group must always remain selected.
In a checkbox group, any number if inputs can be selected or deselected.
Change your HTML to:
<input type="checkbox" name="Xch" value="XCheese " onclick="incrementIndex()">XCheese<br>
And it should work.
i'm trying to populate div with select option but i don't really now where to start...
i have some code to live edit the "title" of the div, but now i want to add to a specific div his option...
Here's the code that i have for now:
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
$(".design-your-system-page-playground-container").show();
for (var i = 0; i < rooms; i++) {
// $("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
// $("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
//
$("<div class='design-your-system-page-rooms targetDiv_" + roomcounter + "'>Room-" + roomcounter + "</div>").appendTo(".design-your-system-page-house");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' class='textInput' lang='targetText_" + roomcounter + "'> <select>Heating<option value='radiator'>Radiator</option><option value='underfloor'>Underfloor</option><option value='electric'>Electric</option></select> <select class='design-your-system-number-of-radiator-select'><option value='0'>0</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option></select> <span>Do you want the room to be smart (footprint) ?<input type='radio' name='smart-yes' value='smart-yes'>Yes</input> <input type='radio' name='smart-no' value='smart-no'>No</input></div></br>").appendTo(".design-your-system-page-edit-room-container");
roomcounter++;
};
if ($('.design-your-system-page-house').find('.design-your-system-page-rooms').length) {
$("#buttonaddrooms").hide();
}
$("input.textInput").on("keyup", function () {
var target = $(this).attr("lang").replace("Text", "Div");
$("." + target).text($(this).val());
});
as you can see, when i click the button, i'll append to the parent as many child divs as the value typed into the textbox and i also create the same number of "row" containing the name and other option (two select and a radio)
i'm already able to live edit the name of the ralative div, but now i want to add to that div also the other options
here a jsfiddle to help you understand what i have and what i want:
http://jsfiddle.net/3cyST/
if is not clear please tell me.
thanks
please check this fiddle:
i made your target variable global to be reusable, i also added a class for your first select element which is selecting
ive updated it and it now appends the value of your test onchange using:
$("select.selecting").on("change", function () {
$("." + target).append($(this).val());
});
you can work for the rest now.
EDIT(for the question of OP on the comment) :
to get value of radio button i'll give you 2 ways :
in Javascript :
if (document.getElementById('ID_OF_RADIO').checked) {
rate_value = document.getElementById('ID_OF_RADIO').value;
}
in jQuery :
$("input[name=RADIO_NAME]:checked").val();
give the select an id, then use
$("#id").on("change",function(){
console.log(this.value);
//whatever you want to do with the value
})
...same for the radio buttons and other options...also note that the radio buttons shouldn't have different names:
<input type='radio' name='radio_{put id here}' value='yes'>Yes</input>
<input type='radio' name='radio_{put id here}' value='no'>No</input>
another thing for the readabillity of the code: try using a template....just put a <noscript> with an id in the code...use some distinctive syntax to put placeholders in it, and replace them at runtime:
HTML:
<noscript id="template">
RoomName: <input type="text" id="roomName_%ROOMID%" />
Do you want...
<input type='radio' name='radio_%ROOMID%' value='yes'>Yes</input>
<input type='radio' name='radio_%ROOMID%' value='no'>No</input>
</noscript>
JS:
for (var i = 0; i < rooms; i++) {
var tplcode = $("#template").html();
tplcode = tplcode.replaceAll("%ROOMID%",roomcounter);
$($.pareHTML(tplcode)).appendTo(".design-your-system-page-edit-room-container");
$("input[name='radio_"+roomcounter+"']").on("change",function(){
console.log("user wants:" + $("input[name='radio_"+roomcounter+"'][checked]").val())
});
roomcounter++;
}
// these functions help replacing multiple occurances
String.prototype.replaceAll = function(find,replace){
return this.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
//escapse all regEx chars, so the string may be used in a regEx
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Fiddle: http://jsfiddle.net/3cyST/4/
I have a page which contains a 10 items(formatted list).Here in this page I need to add check box for each item and add the item as the value to each check box.when the user click on the check box the selected value should be passed to a new page.Can anyone help me how to add a check box for the innerHTML in java script.
Code:
var newsletter=document.getElementById("block-system-main");
var districolumn=getElementsByClassName('view-id-_create_a_news_letter_',newsletter,'div');
if(districolumn!=null)
{
var newsletterall=newsletter.getElementsByTagName('li');
alert(newsletterall[0].innerHTML);
var all=newsletter.innerHTML;
newsletter.innerHTML="<input type='button' onclick='changeText()' value='Change Text'/>";
}
function changeText()
{
alert("dfgsdg");
}
I don't exactly understand what each part of your code is doing, but i'll try and give a general answer:
In your HTML, do something like this:
<form id="myForm" action="nextPage.com">
<div id="Boxes"></div>
</form>
Change the above names to wherever you want your checkboxes to be written.
And your function:
function changeText()
{
for(var i=0 ; i < newsletterall.length ; i++)
{
var inner = document.getElementById("Boxes").innerHTML;
var newBox = ('<input type="checkbox" name="item[]" value="' + newsletter[i] + '>' + newsletterall[i]);
document.getElementById("Boxes").innerHTML = inner + newBox;
}
document.getElementById("myForm").submit();
}
The last line of code submits the checkboxes automatically. If you don't want that, remove that line, and add a submit button to the form myForm.
$('ul#list li').each(
function() {
var me = $(this),
val = me.html(),
ckb = $('<input type="checkbox" />');
ckb.click(function() {
var where=val;
window.location.href='http://google.com/?'+where;
});
me.html('');
me.append(ckb).append($('<span>'+val+'</span>'));
}
);
I have a form. Let's called it myform.
Inside there are checkboxes, such as these two:
<input type='checkbox' name='power_convention[]' value='SOME VALUE #1' />
<input type='checkbox' name='power_evidence[]' value='SOME VALUE #2' />
At the end of the form, there's a textarea.
<textarea id="elm1" name="comments" rows="15" cols="80" style="width: 80%">
If power_convention is checked, I want it to immediately append the value of that checkbox into the comments checkbox with the following structure:
<h3>SOME VALUE #1</h3><br />
Similarly, if power_evidence is clicked, I want it to do the same thing, but obviously after whatever came before it.
How would I go about doing this?
Thanks!
A jQuery solution:
$('input[type="checkbox"]').change(function() {
var val = "<h3>" + this.value + "</h3><br />";
if(this.checked) {
$('#elm1').val(function(i, v) {
return v + val;
});
}
else {
$('#elm1').val(function(i, v) {
return v.replace(new RegExp(val), '');
});
}
});
DEMO
This only works if val does not contain any special regular expressions characters. In this case you would have to escape them.
Update: Actually, you don't need a regular expression here, v.replace(val, '') will be just fine (thanks #Pinkie);
An alternative to regular expressions would be to recreate the content of the textarea:
var $inputs = $('input[type="checkbox"]');
$inputs.change(function() {
var val = "<h3>" + this.value + "</h3><br />";
if(this.checked) {
$('#elm1').val(function(i, v) {
return v + val;
});
}
else {
$('#elm1').val('');
$inputs.not(this).change();
}
});
DEMO 2
jQuery
$('input[name="power_convention[]"]').click(function() {
// assuming you only want the value if the checkbox is being ticked
// not when it's being unticked
if ($(this).is(":checked")) {
$('#elm1').val("<h3>" + this.value + "</h3><br />");
}
});
If you want them both to insert into the same textarea (and they're the only fields on the page that begin with power_) then you can change the selector to use
jQuery's Attribute Starts With selector:
`$('input[name^="power_"]`
Demo on jsfiddle.
First, you will need to add an onClick event handler to your checkbox:
<input type='checkbox' onClick="someFunction(this)" name='power_convention[]' value='SOME VALUE #1' />
Then, up in the head section, in a script tag, put
someFunction(checkbox) {
document.getElementById("elm1").value += "<h3>" + checkbox.value + "</h3>";
}
Here's a jsfiddle
$('input:checkbox[name*=power_]').click(function(){
value = '<h3>' + $(this).val() + '</h3> <br />';
prevVal = $('#elm1').val();
$('#elm1').val(prevVal + value );
});