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.
Related
I am trying to update two cascading drop down inside a table there are many answers on SO for drop downs, but I was unable to find help on cascading updates inside a Table with dynamically added rows.
Given the many rows they all have varying Id's filter #Id does'nt work. So, How do I identify which rows Dropdown triggered the change & cascade the update another Dropdown/cell in the next col of the same row?
There are 2 DropDownList (select box) inside a table row cell. To simplify this, the first is Country -> Second is state. So a user is expected to select the country and then the state.
My pseudo algorithm:
find which one was fired, and which row (unsure if its needed, should I wire in place)
then fire an ajax call... to get the values based on country
update the second drop down with value in the same table row.
Case 1 Change country and then change state.
Case 2 Just change State, but first get the Country value in the first dropdown of the same row.
I know how to get the change and value in a regular page, but how do I get those changes and update the adjacent dropdown.
$(document).on('change', 'select', function(){
var data = $(this).val();
alert(data);
});
Edit, Stephen request to show HTML
<tr>
<td>
//DropDown 1 (Imagine Country)
<span class="projectcodeid">
<select class="form-control" id="Records_1__TCode_Project_ID" name="Records[1].TCode.Project.ID"><option value=""></option>
<option value="1">Plumbing</option>
<option value="2">Modeling</option>
</select></span>
</td>
<td>
//DropDown 2 (Imagine State)
<input type="hidden" name="Records.Index" value="1">
<input class="timecodeid" name="Records[1].TCode.ID" type="hidden" value="5">
<span class="timecode timecodeDdlId"> <select class="form-control timecodeDdlId" id="Records_1__TCode_ID" name="Records[1].TCode.ID"><option value=""></option>
</select></span>
</td>
<td>
<input name="Records[1].DataRecords[0].ID" type="hidden" value="">
<input class="hours" name="Records[1].DataRecords[0].Work" type="text" value="">
</td>
<td>
<input class="bs-checkbox" name="Records[1].DeleteRow" type="checkbox" value="true"><input name="Records[1].DeleteRow" type="hidden" value="false">
</td>
</tr>
Sample image for clarification
Assuming that you can't identify dropdwns by class or anything.
Assuming that every time you change the value in a dropdown you want to update the other dropdown on the same row.
Assuming that you have only two dropdowns per row:
$('table').on('change', 'select', function() {
var $current_dropdown = $(this),
$other_dropdown = $(this).closest('tr').find('select').not(this);
/// perform any task you need with current and other dropdown
});
You need to give both your <select> elements class names and use relative selectors to select the associated element in the same row.
Assuming your html is
<table id="table"> // give this an id attribute
<tbody>
<tr>
<td><select class="country" ....> ..... </select></td>
<td><select class="state" ....> ..... </select></td>
</tr>
</tbody>
</table>
Then your script will be
$('#table').on('change', '.country', function() {
var selectedValue = $(this).val();
var row = $(this).closest('tr'); // get the row
var stateSelect = row.find('.state'); // get the other select in the same row
// make you ajax call passing the selectedValue to your controller
// in the success callback, update the options of stateSelect
$.ajax({
url: ...
data { id: selectedValue },
....
success: function(data) {
stateSelect.empty();
$.each(data, function(item, index) {
stateSelect.append($('<option></option>').val(iem.ID).text(item.Name));
}
}
});
}
Refer also better way to load 2 dropdown in mvc for details of the code for populating cascading dropdownlists (consider caching the options as per the 2nd code example to avoid repeated ajax calls)
I am creating an input to capture data related to fish that are caught. When the submit button is clicked I see a tr quickly show up then disappear, likewise, I see the console.log message show up for a split second then disappear.
Code is posted below, however running the code snippet doesn't look like it does when seen through a browser. I set up a live site for this here: http://fishrecord.jwhdesign.net/
I realize this is probably simple for most of you to figure out, so no need to tell me how dumb I am as I already know that.
Any help is very much appreciated.
function displayFishData() {
var table = document.getElementById("test"); //find "test" AKA the table
var row = table.insertRow(); //add row to that table
row.insertCell(); //insert cell to table
console.log("adding a row to the table");
}
table {
border: 1px solid black;
margin: 0 auto;
width: 80%;
}
<h1>Fish Record</h1>
<form>
Species:
<select>
<option value="blank"></option>
<option value="Northern Pike">Northern Pike</option>
<option value="Largemouth Bass">Largemouth Bass</option>
<option value="Smallmouth Bass">Smallmouth Bass</option>
<option value="Chain Pickerel">Chain Pickerel</option>
<option value="Pike-Pickerel Hybrid">Pike-Pickerel Hybrid</option>
<option value="Panfish">Panfish</option>
<option value="Other">Other</option>
</select>
Weight (lbs):
<input type='number'></input>
Length (inches):
<input type='number'></input>
Comments:
<input rows="1"></input>
<br>
<button onclick="displayFishData()">Submit</button>
</form>
<table id="test">
<thead>
<tr>
<th>Species</th>
<th>Weight (lbs)</th>
<th>Length (inches)</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This is because your button is currently refreshing the page,
If you add
type="button"
to the button it will display an extra tr and show the message in the console
The default value for the type attribute of button element is submit. And thus on click of the button it is submiting the form
Replace
<button onclick="displayFishData()">Submit</button>
to
<button type="button" onclick="displayFishData()">Submit</button>
First of all add the displayFishData() to the form not the button! it would look like this <form onsubmit="displayFishData()"> this would help you to control the form output in a better way.
BTW using <input type="submit" /> is a better practice than <button></button>
And for a simpler data inserting do the following:
var table = document.getElementById("test");
var row = table.insertRow();
var e1 = row.insertCell(0);
var e2 = row.insertCell(1);
// keep adding as much rows as you got
// this change the innerHTML
e1.innerHTML = "the data you got from a form element";
// repeat that
I have a form in a popup, that presents a simple table with header and one row, with a + button the user can click to add (clone) a row.
This works perfectly, the user submits the form, data is read - no problem.
The form is reset after submission with:
$('#entryTable').find("tr:gt(1)").remove(); // keep header and first row
$('#entryForm')[0].reset();
If the user calls the form immediately, the forms "seems" correctly reset, all fields look like new.
If the user clicks on the + (clone) button - it adds the number of rows added previously, and not 1, as if something (but what ?????) was not reset.
my clone function is
$(".cloneprod_add").on('click', function(e) {
e.preventDefault();
var $tr = $(this).closest('.tr_clone'); //only first row has +
var idtr= parseInt($tr.attr("id")); // checked it is always id of row1
var $clone = $tr.clone(true);
cindex++;
$clone.find(':text').val('');
$clone.attr('id', idtr+(cindex) );
$clone.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cindex);
}
});
$tr.after($clone);
$("#addline_"+cindex).addClass("uk-hidden"); // remove +
$("#delline_"+cindex).removeClass("uk-hidden"); // add -
});
cindex is correctly reset to 0 when the form is called again. What else should be reset ? where is my error ?
Thanks for your advices
(EDIT)
I am adding the form . I am using UIkit (www.getuikit.com), a node server and the form comes from a template in jade - I copied the HTML from the browser
<form id="entryForm" action="" class="uk-form uk-form-stacked" >
<div id="entryDialog" class="uk-modal-dialog uk-modal-dialog-large">
<fieldset data-uk-margin="">
<div class="uk-panel uk-panel-box uk-panel-box-primary uk-margin-small-top">
<div class="uk-form-row"><div class="uk-grid"><div class="uk-width-1-1">
<table id="entryTable" class="uk-table">
<thead><tr><th>lot</th><th>code</th><th>num</th>
<th>qte</th><th>unit</th><th>pos</th><th>cont</th>
<th></th></tr>
</thead>
<tbody><tr id="0" class="tr_productclone">
<td><input type="text" name="lot" id="lot_0" class="lot"></td>
<td><input type="text" name="code" id="code_0" class="code"></td>
<td><input type="text" name="num_0" id="num_0" class="num"></td>
<td><input type="text" name="qte_0" id="qte_0" class="qte"></td>
<td><select name="unit_0" id="unit_0" class="unit"><option value="items">pezzi</option></select></td>
<td><select name="pos_0" id="pos_0" class="pos"><option value="1">piece1</option></select></td>
<td><select name="cont_0" id="cont_0" class="cont"></select></td>
<td><button id="addline_0" class="uk-button cloneprod_add"></button>
<button id="delline_0" class="uk-button cloneprod_del"></button></td>
</tr>
</tbody></table></div></div></div></div>
<div class="uk-modal-footer"><button id="btnSave" type="submit" class="uk-button ">save</button></div>
</fieldset></div></form>
I found a solution to my problem. I don't know the why and hows, but at least it works.
I had the impression that the remove was keeping the information of the number of cloned rows and was thus putting that number back. I thought about reloading the table in the modal, so that it would be "fresh without memory".
In the end, I wrote the definition of the table in the js script and not in the Jade template. The table is rebuilt overtime the form is called, and no more memory ghosts.
It works, but I still don't understand why those ghosts.
I want to delete a selected row using jQuery. First, while clicking add button, rows are added dynamically with a delete button. Now I want to delete the selected row.
I am using the following code to add rows dynamically:
$("#btnAdd").on('click', function (){
$('#Time tr').last().after('<tr><td><span style="font-size:14px;">Diplamo/Certificate :</span><input type="textbox" input id="addedValue12" name = "Certificate"></td><td><span style="font-size:14px;">Percentage :</span><input type="textbox" id="addedValue123" name = "CertificatePer"></td></tr>');
});
<input id="btnAdd" type="button" value="add" />
<table id="Time">
<tr>
</tr>
</table>
I am displaying values in a JSP page.
<c:forEach var="var1" items="${empedu.empCertificate}">
Certificate Name:<input value="${var1.certification}" name="Certificate" type="text" title="Only Text Allowed" pattern="[a-zA-Z\s'.,#:&?!()$#/\\]+" />
Percentage: <input value="${var1.percentage}" name="CertificatePer" style="width: 100px;" type="text" max="100" />
<input type="button" id="deleteRow" name="delete" value="delete" /><br/>
</c:forEach>
It is displayed on screen like this:
Here, If I click the third row, I want to delete the third row. How can I do this?
$("#Time").on("click", ".delete", function(){
$(this).closest("tr").remove();
});
Assuming delete is the class of the delete button. I have used .on as the rows and thus delete buttons are dynamically added.
This is picking the closest tr from the clicked delete button, and removing it.
Working Fiddle
1st: Id must be unique so don't use id for more than one element .. use class instead
2nd: while you append rows you need to jQuery event delegation ...
$('#Time').on('click' , '.delete' , function(){
// change .delete_btn with your delete btn class
$(this).closest('tr').remove();
});
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];
}
}