How to insert selected radio button value into table cell - javascript

I have 5 radio buttons
<input type="radio" id="rating">1
<input type="radio" id="rating2">2
<input type="radio" id="rating3">3
<input type="radio" id="rating4">4
<input type="radio" id="rating5">5
I have one table
<table id="myTableData" border="1" style="width:100%">
<tr id="templateRow">
<th>Ratings</th>
</tr>
</table>
One add button
<input type="button" id="add" value="Add" onclick="addRadioValue()">
I've written the code to dynamically add rows to the table, but when I select a radio button and then I click on the add button, the value of the selected radio button should get inserted into a new cell within table Ratings.
I am able do this thing for a text box, but I'm not able to do it for a radio button.
Can anyone help me?

you can use querySelector('input[name="rating"]:checked')
Java script
function addRow() {
var myName = document.getElementById("name");
var auther = document.getElementById("auther");
var publish = document.getElementById("publish");
var rating = document.querySelector('input[name="rating"]:checked');
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML=count ;
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= auther.value;
row.insertCell(3).innerHTML= publish.value;
if(rating.checked)
row.insertCell(4).innerHTML= rating.value;
else
row.insertCell(4).innerHTML= "";
count=count+1;
}
Here is my Demo

Your problems were that you didn't have name set on the radios and that you were trying to grab the selected radio with a get id statement. You actually need to grab the radio elements by name and do a loop to check which is selected.
Working jsfiddle: http://jsfiddle.net/cv4u0nf9/4/
The loop i inserted
var ratings = document.getElementsByName("rating");
for (var i=0; i<ratings.length; i++) {
if (ratings[i].checked) {
rating = ratings[i];
}
}

Related

How enable disabled checkbox of a specific div?

Here I'm using firebase to display all driver info one by in one div. I have 6 div(i.e 6 object in driver reference) & each div has a checkbox with enabled/disabled option. I want operate checkbox in such way that if I click checkbox of 1st div it will change in only in 1st div,if I click checkbox of 2nd div it will change in only in 2nd div,& so on but the problem is when I clicked any checkbox only 1st checkbox is change... How can I overcome this...thanks in advance
<script>
function contactHtmlFromObject(Key, Driver){
console.log(Key,Driver);
if(Driver.Gender=='Male'){
html +='<input type="checkbox" id="disablecheckbox" onclick="loaddisable(\''+Key+'\')"><span id="toggle">Enabled</span>';
}
else{
html +='<input type="checkbox" id="disablecheckbox" onclick="loaddisable(\''+Key+'\')" checked><span id="toggle">Disabled</span>';
}
}
function loaddisable(Key) {
var toggle= document.getElementById("toggle");
var dcb= document.getElementById("disablecheckbox");
var Refdis = firebase.database().ref("Driver/"+Key);
Refdis.on("value", function(snapshot) {
if (dcb.checked == true){
toggle.innerHTML="Disabled";
}
else {
toggle.innerHTML="Enabled";
}
});
}
As the nice folks from the comments already suggested, your IDs aren't unique. That's the whole purpose of a ID, right ?! :)
So your JS functions look at the first element with the id, does what it supposed to do with it, and stops.
Instead of using id, I used a class as the selector and built two functions:
One for enabling the checkbox
One for disabling them.
I achieved that simply by looping over the elements that have that specific class name.
Check out the code snippet and see if it works for you ;)
function disable(obj){
const elem = document.getElementsByClassName("checks");
for(let i = 0; i < elem.length; i++){
if(obj != elem[i]){
elem[i].disabled = true;
}
}
}
function enable(obj){
const elem = document.getElementsByClassName("checks");
for(let i = 0; i < elem.length; i++){
if(obj != elem[i]){
elem[i].disabled = false;
}
}
}
Checkbox 1: <input type="checkbox" class="checks"> <br>
Checkbox 2: <input type="checkbox" class="checks"> <br>
Checkbox 3: <input type="checkbox" class="checks"> <br>
Checkbox 4: <input type="checkbox" class="checks"> <br>
Checkbox 5: <input type="checkbox" class="checks"> <br>
<button onclick="disable(this)">Disable All</button>
<button onclick="enable(this)">Enable All</button>

Radio button selection is not working as expected

I am facing an issue with the existing code which is using html and JS. The page has a html table which has a radio button and 4 other fields. The table is created dynamically when we set values through controller. Also I can add new rows in the table which is done completly through JS. Now the problem is I inserted 2 rows from controller and added a new row through a button click. So I have 3 radio button now. If I select one radio button among the controller inserted row it selects only one, which is fine, If I select the 3rd one I can see two selected radio button, which is not correct. In any case it should select only one. when I take view source I am not seeing the entry for the javascript added new row, so I hope the problem is because of the Id generated ? please let me know how can I solve this issue?
Java controller
List <MyQuestion> fetchedQuestions = AppImpl.getMyQuestions(id);
for (int index=0; index< fetchedQuestions.size() ; index++){
MyQuestion questionsToAdd= fetchedQuestions.get(index);
questionList.add(questionsToAdd);
}
myqstntemplate.setMyQuestions(questionList);
templatebean.setQuestionTemplate(myqstntemplate);
}
JScode
function addRow(){
isDirty=true;
if(document.getElementById('value').value != 'value'){
rowNumber = document.getElementById('questionsSize').value;
document.getElementById('value').value='value';//other option is novalue
}
var questionId=document.getElementById('questionsSize').value;
questionId=parseInt(questionId)+1;
document.getElementById('questionsSize').value = questionId;
var newRow = $('<tr/>').attr('id', 'row' + rowNumber);
//Add some HTML to the row
newRow.html('<td><input type="hidden" id="newQuestion'+rowNumber+'" value="'+questionId+'"/><input id="question" name="question" type="radio" style="width:20px;" value="" onclick="setSelectedQuestion(\''+rowNumber+'\',\'new\')"/></td><td class="newRow" align="center" style="vertical-align: middle;">'+questionId+'<input type="hidden" value="newQuestion"/></td> <td colspan="2"><input style="width: 397px;" id="myQstnTemplate.questions['+rowNumber+'].question" name="myQstnTemplate.questions['+rowNumber+'].question" type="text" value="" maxlength="256" onclick="enableDirty()" style="text-align:left;"/><div id="pencil" title="Edit helptext" class="pencil-img fltRight" style="border: 0pt;padding-right: 15px; " onclick="displayHelpText('+rowNumber+',\'new\');return false;"></div><input id="myQstnTemplate.questions['+rowNumber+'].questionId" name="myQstnTemplate.questions['+rowNumber+'].questionId" type="hidden" value="-1" /><input style="width: 350px;" id="myQstnTemplate.questions['+rowNumber+'].helptext" name="myQstnTemplate.questions['+rowNumber+'].helptext" type="hidden" value="" onclick="enableDirty()" style="text-align:left;"/></td><td><select style="width:100px;" id="myQstnTemplate.questions['+rowNumber+'].schemeId" name="myQstnTemplate.questions['+rowNumber+'].schemeId"><option value="-1">Select</option><c:forEach var="answer" items="${myqstionTemplateBean.answerTypes}"><option title="${answer.questions}" value="${answer.displaySchemeId}">${answer.answerTypeName}</option></c:forEach></select></td> <td><div><input type="hidden" id="question'+rowNumber+'" name="question'+rowNumber+'" value="'+rowNumber+'"/><select id="myQstnTemplate.questions['+rowNumber+'].ansId" name="myQstnTemplate.questions['+rowNumber+'].ansId" style="width:100%"><option value="-1">Select</option><c:forEach var="ansId" items="${myqstionTemplateBean.ansIds}"><option value="${ansId}" <c:if test="${ansId eq question.ansId}">selected</c:if>>${ansId}</option></c:forEach></select></div></td>');
//Append the new row to the body of the #myTable table
$('#qstionTable tbody').append(newRow);
//Iterate row number
rowNumber++;
}
If you want all the radio button working together you should have the same name for each in your template.
Check that.
Edit:
If several radio button can be selected it is because their name are differents. Your radio' name must not depend of the rowNumber. Set a hard name, not a variable name.
Check that.

html javascript autocomplete not working with dynamically added textboxes

Hi when I use jquery autocomplete on 1 textbox it work, but when i dynamically add new textbox these new textbox dont have the same autocomplete
Here is my javascript autocomplete
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script type="text/javascript" src="dynamicscript.js"></script>
<script>
$(document).ready(function(){
$(".DRUG_NAME").autocomplete("gethint.php", {
selectFirst: true
});
});
</script>
this is what i am dynamically adding each time, html code
<form method="post">
<p>
<input type="button" value="Add Drug" onClick="addRow('dataTable')" />
<input type="button" value="Remove Drug" onClick="deleteRow('dataTable')" />
</p>
<table id="dataTable" class="form" border="1">
<tbody>
<tr>
<p>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" />
</td>
<td>
<label>Drug</label>
<input type="text" required="required" name="DRUG_NAME[]" id="DRUG_NAME" class="DRUG_NAME">
</td>
</p>
</tr>
</tbody>
</table>
<input type="submit" value="Save" />
</form>
this is the javascript dynamically add / remove row i even added the autocomplete function after my addrow to try and get the jquery autocomplete to be called each time after i add row but it still does not work
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 5) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
} else {
alert("Maximum Drug is 5");
}
$("#DRUG_NAME").autocomplete("gethint.php", {
selectFirst: true
});
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount < 1) { // limit the user from removing all the fields
alert("Nothing to Remove");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
any ideas?? tx
The following code (from your post) attaches events to the elements with class DRUG_NAME that currently exist on the page:
$(".DRUG_NAME").autocomplete("gethint.php", {
selectFirst: true
});
When you dynamically add an element that selector will be updated, but the events still won't be attached, see this answer: Event binding on dynamically created elements?
Using that answer, together with the one #LcKjus linked in his answer (Bind jQuery UI autocomplete using .live()), I believe this will work for you (replace the code above with this snippet to test):
$(".DRUG_NAME").on("focus", function (event) {
$(this).autocomplete(options);
});
This may run the autocomplete code multiple times (if the user refocuses the input field), though, so be aware of that.
P.S. As others have noted, it is unwise to have multiple elements with the same id on the same page.
You probably need a live binding.
Take a look at this post:
Bind jQuery UI autocomplete using .live()
The problem is that you are creating elements with the same ID DRUG_NAME and then you are applying autocomplete selecting the field by ID.
Remove the id from the input field of the first row, as it is going to be replicated:
<input type="text" required="required" name="DRUG_NAME[]" class="DRUG_NAME">
Use the class selector when you create new rows:
$(".DRUG_NAME").autocomplete("gethint.php", {
// ^^
selectFirst: true
});
The code to bind the autocomplete is being run on document ready. You need to run it again after you add the dynamic text boxes (maybe create a bindAuto() function or whatever, and run it from both places).

How to add items to a list in similar check box format from user input

I am trying to make an editable check list, using check boxes. One feature I would like is for users to be able to add their own items to this list.
With the help of another user, I have got this far:
HTML:
<table id="myTable">
<tr>
<td>
<label for="checkbox65">
<input name="checkbox65" class="checkbox65" type="checkbox" />
Get directions for where you are going
</label>
</td>
</tr>
<tr>
<td>
<fieldset data-role="controlgroup">
<label for="textinput4">
Add new item
<input name="new_item" id="textinput4" placeholder="" value="" type="text" />
</label>
</fieldset>
<button id="add">Add</button>
</td>
</tr>
</table>
Javascript:
$('#add').on('click', function (e) {
var $this = $(this);
var $firstRow=$this.closest('table').find('tr:first');
var $newRow = $firstRow.clone();
$newRow.find(':input').prop('checked', false);
$newRow.insertAfter($firstRow);
});
What I'm trying to get is something that looks a bit like this:
What I want
But at the moment it just repeats the original check box with label.
Assuming you need to set the text next to the checkbox to what you enter in the input box, you can do:
$('#add').on('click', function (e) {
var $this = $(this);
var $firstRow=$this.closest('table').find('tr:first');
var $newRow = $firstRow.clone();
var input = $newRow.find(':input').remove();
input.prop('checked', false);
$newRow.empty().append(input).append(' '+$('#textinput4').val());
$newRow.insertAfter($firstRow);
});​
Demo: http://jsfiddle.net/VHe6C/
You can add the text box value for the check box
$(document).ready(function(){
$("#addbutton").on("click",function(){
if ($("#goingtoadd").val()!="")
document.getElementById('adding').innerHTML+='<br/><input name="checkbox65" class="checkbox65" type="checkbox" />'+$("#goingtoadd").val();
$("#goingtoadd").val("");
})
});
See this Fiddle for Demo
If anyone is interested in a pure javascript based solution here is it:
document.querySelector('#add').addEventListener('click', function(e){
var table = this.parentNode.parentNode.parentNode,
rowsLen = table.rows.length,
beforeLastRow = table.rows[rowsLen - 2],
inputToAdd = document.querySelector('#textinput4');
var newRow = beforeLastRow.cloneNode(true),
input = newRow.querySelector('input');
input.checked = false;
var label = newRow.querySelector('label');
label.innerHTML = "";
label.appendChild(input);
label.appendChild(document.createTextNode(inputToAdd.value));
inputToAdd.value = "";
table.insertBefore(newRow, table.rows[rowsLen - 1]);
}, false);
Here is a jsFiddle to test it out:
http://jsfiddle.net/subhamsaha1004/2G9Qv/

selecting only one from multiple checkboxes in a display tag row

I am using a display table in my jsp page.. It is like...
<display:table name="${MyList}" pagesize="10" requestURI="" sort="page">
<display:setProperty name="paging.banner.placement" value="bottom" />
<display:column property="Language" sortable="true" title="Name" />
<display:column title="Read">
<input type="checkbox" name="ReadOnly" id="1" onChange="toggle(this);">
</display:column>
<display:column title="Write">
<input type="checkbox" name="Write" id="2" onChange="toggle(this);">
</display:column>
<display:column title="Speak">
<input type="checkbox" name="Speak" id="3" onChange="toggle(this);">
</display:column>
</display:table>
It was working fine. And then i need to make only one combo box to be selected in each row. For that i used the javaScript function
<script type="text/javascript">
function toggle(chkBox) {
alert("chk----"+chkBox);
checkboxes = document.getElementsByTagName("input");
alert("hai-----"+checkboxes);
var isChecked = chkBox.checked;
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = false;
}
if (isChecked) {
chkBox.checked = true;
}
}
</script>
But now i can only select one of the whole checkboxes in myList. I want to select only one combobox from each row..
Firstlt i must say.. I dont need the radio button there.
Is it possible? and how can i make my code to achieve it???

Categories