i want to iterate through a group of radio buttons generated dynamically and get their labels, but when i attempt to print their values nothing appears, see this script demo for an example http://jsfiddle.net/HaBhk/20/ and here's my html where the generated buttons will go
<div data-role="content">
<div data-role="collapsible" data-inset="true">
<h1>AddVote</h1>
<div data-role="fieldcontain" >
<input type="text" name="name" id="question" value="" /><br>
<div data-role="controlgroup" data-type="horizontal" >
<label for="name"><a href="" id="AddButton" data-role="button"
data-icon="plus">Add</a><a href="" id="RemoveButton" data-role="button"
data- icon="delete">Delete</a>
</label>
<input type="text" name="option" id="option" value="" /><br>
</div>
<div data-role="fieldcontain">
<form name="OptionsForm" id="InputForm" method="get">
<div id="after" data-role="controlgroup">
/////Generated radio buttons goes here
</div>
</form>
</div>
<a href="#approve" id="publishButton" data-role="button"
data-inline="true"data-transition="flip">Preview</a>
</div><!-- /content -->
below is my script to get radio buttons values:
$('#publishButton').click(function(){
var result
var y=document.getElementById('question').value
var form='<Question value=' + y + '/>'+'<br>'
alert(form);
$('input:radio').each(function() {
var value=$('input:radio').val()
'<option value='+value + '/>'+'<br>'
alert(result);
});
Here is some sample code that will return the relevant labels for the radio options.
var labels = [];
$('input:radio').each(function(){
labels.push($('label[for='+$(this).attr('id')+']').text());
});
alert(labels);
$('#publish').click(function () {
var labs = $(':radio + label'),
alertString =[];
for (var i = 0, labLen = labs.length; i < labLen; i += 1) {
alertString[i] = labs[i].id;
};
alert(alertString.join("\n"));
});
Try this: http://jsfiddle.net/HaBhk/24/
<input type="text" name="option" id="option" value="" /><br>
<div id="AddButton" data-role="button" data-inline="true">Add</div>
<div id="RemoveButton" data-role="button" data-inline="true">remove</div>
<div id="publishButton" data-role="button" data-inline="true">publish</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup"><legend>Choose an Option:</legend><br><br>
<div id="after">
</div>
</fieldset>
</div>
<script type="text/javascript">
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<div><input type="radio" name="option1" id="'+id+ '" value="1"/><label for="' + id + '">'+label + '</label></div>'));
}
$('#AddButton').click(function() {
var x = document.getElementById('option').value;
createRadioElement(this, $('#option').val());
});
$('#RemoveButton').click(function() {
$('#after').children().children("input[checked='checked']").parent().remove();
});
$('#publishButton').click(function() {
var result;
$('#after input:radio').each(function() { // only radio buttons in #after
var value = $(this).next('label').html();
alert(value);
});
});
</script>
Related
Why does my Priority checkbox return 'on' as a result after selecting either the 'Important' or 'Unimportant' checkbox? Why does it not return either 'Important' or 'Unimportant'?
Also, why does my Category radio selection only return the correct selection the first time I input and click the add button - on every subsequent attempt, the return is blank for Category. All the other input options work correctly.
var $addButton = $(".btn-primary");
var $removeButton = $(".btn-danger");
var $todoList = $(".uncomplete");
var $doneList = $(".completed");
//Take Text Input and Add <li> to To Do List
$addButton.on("click", function(){
//Creating object Variables
var $sort = $(".sort").val();
var $newTask = $(".newTask").val();
var $taskDescr = $(".taskDescr").val();
var $taskDate = $(".taskDate").val();
// var $category= $(".category").val();
var $category= $("input[type='radio'][name='category']:checked").val();
//var $importance = $("input[type='checkbox'][name='importance']:checked").val();
var $importance = $('<input type="checkbox" name="importance"/>').val();
var $newTaskString = $sort + ", " + $taskDescr + ", " + $newTask + ", " + $taskDate + ", " + $category + ", " + $importance + " ";
var $todoList = $(".uncompleted");
//call append method on $todoList
$todoList.append("<li>" + $newTaskString + "<button><span> Done</span></button><button><span> Remove</span></button></li>").addClass("todo");
//add styles to button added to DOM by append
var $span = $(".todo button span");
var $button = $(".todo button");
$button.addClass("btn btn-success");
$span.addClass("glyphicon glyphicon-ok");
$("input").val("");
})
//When Success button Clicked, remove task from to do list and append to completed tasks
var $doneButton = $(".btn-success");
$(".uncompleted").on("click", ".btn-success", function(){
var $completedTask = $( this ).parent("li").text();
$(this).parent("li").remove();
$doneList.append("<li>" + $completedTask + "<button><span> Remove</span></button></li>").addClass("done");
$(".done button").addClass("btn btn-danger");
$(".done button span").addClass("glyphicon glyphicon-remove");
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list-wrap" contenteditable="false">
<div class="list-inner-wrap">
<h2 class="title">ToDo List</h2>
<h3 class="title">Add Task</h2>
<label for="sort">Sort Order:</label><input type="text" class="sort" name="sort" id="sort" value="" placeholder="A,B,C,etc.">
<br>
<label for="task-name">Task Name:</label><input type="text" class="newTask" name="task-name" id="task-name" value="" placeholder="My task...">
<br>
<label for="task-descr">Task Descr:</label><input type="text" class="taskDescr" name="task-descr" id="task-descr" value="" placeholder="Buy milk...">
<!--<h4>Date</h4>-->
<br>
<label for="task-date">Start Date:</label><input type="text" class="taskDate" name="task-date" id="task-date" value="" placeholder="dd/mm/yyyy">
<br>
<form method="POST" action="..." name="radiodemo" id="radiodemo" onsubmit="getCategory();">
<label for="category"> Category:</label>
<input type="radio" id="grocery" name="category" value="Grocery" class="category" checked="checked">
<label for="grocery">Grocery</label>
<input type="radio" id="work" name="category" value="Work" class="category">
<label for="work">Work</label>
<input type="radio" id="chores" name="category" value="Chores" class="category">
<label for="chores">Chores</label>
<input type="radio" id="finance" name="category" value="Finance" class="category">
<label for="finance">Finance</label>
<br>
</form>
<label for="importance">Priority:</label>    Important<input type="checkbox" class="importance" name="important" id="important" value="Important">
<label for="importance"></label>Unimportant<input type="checkbox" class="importance" name="unimportant" id="unimportant" value="Unimportant">
<br>
<button class="btn btn-primary">
<span class="glyphicon glyphicon-plus"> Add</span>
</button>
<br>
<h3 class="title">To Do</h2>
<h6><i>Click task item to edit or modify</i></h6>
<ul class="uncompleted" id="id01"><!--contenteditable="true"-->
<li>Need to be completed task
<button class="btn btn-success"><span class="glyphicon glyphicon-ok"> Done</span>
</button>
<button class="btn btn-danger"><span class="glyphicon glyphicon-remove"> Remove</span>
</button>
<br>
</li>
</ul>
I am struggling with this thing for the last few days and trying to obtain specific div details. It was resolved actually and here is the working one - Obtain Related Div Text with jQuery. So if you have seen it, I was using individual buttons for each div section as follows:
<div class="divs">
<div class="heading">
<div class="h2Val"> //Trying to retrieve this value - The id
1
</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div>
<input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
//Another one is this - CheckBox value
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
<div>
<input type="button" class="btn" value="Get Value" /> //This is the button that was assigned with every div
</div>
</div>
</div>
But now, I am trying to separate the buttons and used anchor tag that's out of the parent div class divs to retrieve those values . But the issue is, it doesn't get the id and values of individual divs. Here is the code snippet:
$(document).ready(function() {
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
$("#next").click(function() {
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$("#prev").click(function() {
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$(".button").click(function() { //This doesn't get the id and value of heading div
var $container = $(this).closest('.heading')
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function(){
return this.value
}).get();
console.clear()
console.log('ID: ' + id +' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="divs">
<div class="heading">
<div class="h2Val">
1
</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div>
<input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
</div>
<div class="heading">
<div class="h2Val">
2
</div>
<div>Who invented computer?</div>
<div class="heading2">
<div><input type="checkbox" id="val3" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val4" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val5" class="cbCheck" name="val5" value="Sir Isaac Newton" />Sir Isaac Newton</div>
</div>
</div>
</div>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
So I tweaked a bit with the following but it retrieves all the selected div values at a time rather than individual:
$(".button").click(function() { //This doesn't get the id and value of heading div
var $container = $('.divs').children().closest('.heading')
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function(){
return this.value
}).get();
console.clear()
console.log('ID: ' + id +' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
});
});
Any better way or solution to resolve it?
Update 1: Expected output - When checked on first option and clicked Next, it should show result as follows:
ID: 1 has 1 checked
Values: London
Then when second question comes and the same should happen:
ID: 2 has 1 checked
Values: Charles Babbage
You can get length of .divs and then declare some variable which will have value 0 .So, whenever next button is clicked you can check if the variable value if less then the length of .divs and depending on this either increment value by 1 or start counter again from 0.
Demo Code :
$(document).ready(function() {
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
$("#next").click(function() {
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$("#prev").click(function() {
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
//declare
var indexes = 0;
$(".button").click(function() {
//get div length
var lengths = divs.length;
//pass indexes value to get required div
var $container = $('.divs').children().eq(indexes);
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function() {
return this.value
}).get();
console.clear()
console.log('ID: ' + id + ' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
//checking if indexes value is less then length of div
if (indexes < (lengths-1)) {
//increment
indexes++;
} else {
//start from 0
indexes = 0;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="divs" datas="abc">
<div class="heading">
<div class="h2Val">
1
</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div>
<input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
</div>
<div class="heading">
<div class="h2Val">
2
</div>
<div>Who invented computer?</div>
<div class="heading2">
<div><input type="checkbox" id="val3" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val4" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val5" class="cbCheck" name="val5" value="Sir Isaac Newton" />Sir Isaac Newton</div>
</div>
</div>
</div>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
The requirement is to dynamically add each li element as and when user click on "add row" button". And when User enters any value in field1, an ajax call with this value as parameter is made to server and the return value is set in the next 2 fields.
In focus lost method, when I try to retrieve the user entered value, the input field value is always returned as EMPTY or the default value which I set in the source code and not the user modified value.
The row ids are given unique like f1_edit_row1, f1_edit_row2 etc. Please let me know on why I dont get the value.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script src="js/jquery-1.12.4.js"></script>
<title>Insert title here</title>
</head>
<body>
<ul id="Rows_Edit">
<li id="EditRow1">
<div class="row">
<div class="col-md-3 Field1">
<span>Field1</span><input type="text" class="form-control field1"
id="f1_edit_row1" onfocusout="focusLost_edit('1')" name="field1"
placeholder="1234">
</div>
<div class="col-md-3 Field2">
<span>Field2</span><input type="text" class="form-control"
id="f2_edit_row1" name="field2" placeholder="123"
disabled="disabled">
</div>
<div class="col-md-5 name">
<input type="text" class="form-control" id="field3_edit_row1"
placeholder="ABC" disabled="disabled">
</div>
<div class="col-md-1 icons" id="btn_row1">
<input type="button" class="addbtn" id="btn_row1" name="Add" value="Add Row" onclick="addButtonClick()">
<!-- <i class="fa fa-plus-square" id="btn1_edit" aria-hidden="true"></i> -->
</div>
</div>
</li>
</ul>
<div></div>
<div></div>
<div></div>
<div class="updatebutton">
<input type="submit" id='submit-button_edit' class="btn btn-default" value="Update" onclick="updateBtnClick()">
</div>
<div class="cancelbutton">
<input type="button" id='cancel-button_edit' class="btn btn-default" value="Cancel">
</div>
</body>
</html>
<script type="text/javascript">
function focusLost_edit(rowNo){
var id = "f1_edit_row" + rowNo;
var value = document.getElementById(id).value;
console.log(id, " Value:[", value, "]");
// API Code here
var returnvalue = "TEST";
var id1 = "#f2_edit_row" + rowNo;
$(id1).val(returnvalue);
console.log(id1, " Return Value:[", returnvalue, "]");
var returnvalue1 = "TESTING";
var id2 = "#field3_edit_row" + rowNo;
$(id2).val(returnvalue1);
console.log(id2, " Return Value1:[", returnvalue1, "]");
}
function addButtonClick(){
console.log("Add Button Click");
// Code to add rows here
}
function updateBtnClick(){
console.log("Update Button Click");
$('ul#Rows_Edit li').each(function() {
var id = $(this).attr('id');
var rowNo = id.substring(7);
var id1 = "#f1_edit_row" + rowNo;
var value1 = $(id1).val();
var id2 = "#f2_edit_row" + rowNo;
var value2 = $(id2).val();
var id3 = "#field3_edit_row" + rowNo;
var value3 = $(id3).val();
console.log("Value1:[", value1, "] Value2:[", value2, "]Value3:[", value3), "]";
});
// Code to send value to server here
}
</script>
Use this in your function call.
function focusLost_edit(rowNo){
var id = "f1_edit_row" + rowNo;
var value = document.getElementById(id).value;
console.log(id, " Value:[", value, "]");
// API Code here
var returnvalue = "TEST";
var id1 = "#f2_edit_row" + rowNo;
$(id1).val(returnvalue);
console.log(id1, " Return Value:[", returnvalue, "]");
var returnvalue1 = value;
var id2 = "#field3_edit_row" + rowNo;
$(id2).val(returnvalue1);
console.log(id2, " Return Value1:[", returnvalue1, "]");
}
function addButtonClick(){
console.log("Add Button Click");
// Code to add rows here
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="shipToRows_Edit">
<li id="EditRow1">
<div class="row">
<div class="col-md-3 Field1">
<span>Field1</span><input type="text" class="form-control field1"
id="f1_edit_row1" onfocusout="focusLost_edit('1')" name="field1"
placeholder="1234">
</div>
<div class="col-md-3 Field2">
<span>Field2</span><input type="text" class="form-control"
id="f2_edit_row1" name="field2" placeholder="123"
disabled="disabled">
</div>
<div class="col-md-5 name">
<input type="text" class="form-control" id="field3_edit_row1"
placeholder="ABC" disabled="disabled">
</div>
<div class="col-md-1 icons" id="btn_row1">
<input type="button" class="addbtn" id="btn_row1" name="Add" value="Add Row" onclick="addButtonClick()">
<!-- <i class="fa fa-plus-square" id="btn1_edit" aria-hidden="true"></i> -->
</div>
</div>
</li>
</ul>
I have a rather long complicated form to be used to record field data. One section of the form requires the ability to add a "Field Blank" section with no data recorded AND the ability to add a duplicate section where everything (including the data from the field blank section) is duplicated. The only different thing that would change on the duplicate would be the SampleID
The field blank script
<script>
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
</script>
The duplicate script
<script>
$(document).ready(function(){
var template_index=0;
$("#add_FieldDup").click(function(){
template_index++;
$(this).parent().before($("#template").clone().attr("id","template" + template_index));
$("#template" + template_index).css("display","inline");
$("#template" + template_index + " :input").each(function(){
$(this).attr("name",$(this).attr("name") + template_index);
$(this).attr("id",$(this).attr("id") + template_index);
});
$("#remove_Dup" + template_index).click(function(){
$(this).closest("fieldset").remove();
});
});
});
</script>
My form
<h3>Water Samples</h3>
<fieldset id="template"> <!--for the duplicate-->
<div id="template"> <!--for the duplicate-->
Sample ID: <input type="text" id="SampleID" name="SampleID"></div>
<div class="_40" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label> Collection Method</label><br />
<input type="radio" id="radGrab" value="grab" name="Collection" />
<label for="radGrab">Grab</label>
<input type="radio" id="radEWI" value="EWI" name="Collection" />
<label for="radEWI">EWI</label>
</div>
<fieldset> <!--For the field blank-->
<div id="readroot" class="hidden"> <!--For the field blank-->
QA Sample ID:<input type="text" id="QASampleID" name="QASampleID">
<div class="_30" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label>Collection Method</label><br />
<input type="radio" id="radGrab1" value="Grab" name="Collection1" />
<label for="radGrab1">Grab</label>
<input type="radio" id="radEWI1" value="EWI" name="Collection1" />
<label for="radEWI1">EWI</label></div>
</div>
<label class="analysis-label" for="analysis">Analyte:</label>
<select class="analysis" id="analysis" name="analysis" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "TN">TN</option>
<option value = "TP,NO2+3">TP,NO2+3</option>
</select>
<label class="preserve-label" for="preserve">Preserved</label>
<select class="select_preserve" id="preserve" name="preserve" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "HNO3">HNO₃</option>
<option value = "H2SO4">H₂SO₄</option>
</select>
<label class="cool-label" for="cool">Cooled</label>
<select class="select_cool" id="cool" name="cool" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "Ice">Ice</option>
<option value = "Frozen">Frozen</option>
<option value = "None">None</option>
</select>
</div> <!--Fieldblank-->
</fieldset> <!--Fieldblank -->
<hr /><span id="writeroot"></span>
</div> <!--duplicate template-->
</fieldset> <!--duplicate template-->
<button type="button" data-theme="b" data-icon="plus" id="moreFields" onclick="moreFields()">ADD FIELD BLANK</button>
<button type="button" data-theme="b" data-icon="plus" id="add_FieldDup">ADD FIELD DUP</button>
I got the duplicate to work (when the field blank wasn't hidden) but I cannot get the field blank to work. Any assistance would be greatly appreciated!
You should extract your javascript from your dom, put it in separate js and make function work in any of this blocks, create class="template" block and inside give any needed interaction buttons and inputs classes so there can exist multiple parent elements with same inside structure... then cloning does not get in a way of your interaction logic.
In js go like:
$(document).ready(function() {
$(".template .interaction_button_one").on('click', function(){
//... here you go traversing like
$(this).parents('.template').find('.some_important_div').show();
})
});
Notice .on(), this is delegation, and it will give same interaction bindings to all of your elements.
i have a problem in grouping a dynamically generated radio buttons into a jQuery Mobile control group, i generate the radio buttons and append them into a but they are dispalayed separetly although there warping contains a 'controlgroup' data-role, here's my HTML:
<div data-role="collapsible" data-inset="true">
<h1>AddVote</h1>
<div data-role="fieldcontain" >
<form id="voting" action="get">
<label for="name"> <strong>Question:</strong></label>
<input type="text" name="name" id="name" value="" /><br>
<label for="name"><div id="AddButton" data-role="button" data-inline="true">AddOptions</div></label>
<input type="text" name="option" id="option" value="" /><br>
<div id="RemoveButton" data-role="button" data-inline="true">RemoveOptions</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend> <strong>Choose an Option:</strong></legend><br><br>
<fieldset data-role="controlgroup">
<div id="after" data-role="controlgroup" >
///////////////////////Generated radio buttons goes here//////////////////////
</div>
</fieldset>
</fieldset>
</div>
</div>
<a href="#" data-role="button" data-inline="true" >Publish</a>
</form>
and here's the script code:
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<input />', {
'type': 'radio',
'name': 'option1',
'id': id,
'data-role': 'controlgroup',
'data-theme':'e',
'value': '1'
}));
$('#after').append('<label for="' + id + '">'
+ label + '</label><br />').trigger('create');
}
$( '#admin' ).live( 'pageinit',function(event){
$('#AddButton').click(function(){
var x = document.getElementById('option').value;
createRadioElement(this,$('#option').val(),true);
});
Perhaps I don't understand the question correctly but is it the <br /> between the radiobuttons that concerns you? If this is the case then just replace this:
$('#after').append('<label for="' + id + '">'
+ label + '</label><br />').trigger('create');
with this:
$('#after').append('<label for="' + id + '">'
+ label + '</label>').trigger('create');
Also I believe that your <form> and <div> tags are incorrectly nested.