Find each checked radio button value on separate forms - javascript

Right now, I am storing two forms full of radiobuttons in separate div tags.
I need to be able to compare the checked radiobuttons from the left and right div tag.
Right now, I have this code to look for the checked values in the right and left div tags, however; it's checking the left div tag radiobutton values twice.
$('#btn').click(function() {
$("#right input[type='radio']:checked").each(function() {
var idVal = $(this).attr("id");
var rightcity = ($("label[for='"+idVal+"']").text());
console.log(rightcity);
$('#rightcity').text(rightcity);
});
$("#left input[type='radio']:checked").each(function() {
var idVal = $(this).attr("id");
var leftcity = ($("label[for='"+idVal+"']").text());
console.log(leftcity);
$('#leftcity').text(leftcity);
});
});
Any idea on how to specifically run this query for the right div tag values as well?

1st : if radios with same group in left/right . no need to loop through
2nd you can try this
$('#btn').click(function() {
var rightId = $("#right input[type='radio']:checked").attr("id");
var leftId = $("#left input[type='radio']:checked").attr("id");
var rightcity = $("label[for='"+rightId+"']").text();
var leftcity = $("label[for='"+leftId+"']").text();
console.log(rightcity);
$('#rightcity').text(rightcity);
console.log(leftcity);
$('#leftcity').text(leftcity);
});
maybe you don't need to get ids .. if your html
<label></label>
<input type="radio"/>
you can directly use .prev() instead of getting ids
var rightcity = $("#right input[type='radio']:checked").prev('label').text();
var leftcity = $("#left input[type='radio']:checked").prev('label').text();
and if its
<input type="radio"/>
<label></label>
use .next()
var rightcity = $("#right input[type='radio']:checked").next('label').text();
var leftcity = $("#left input[type='radio']:checked").next('label').text();
and about (be able to compare the checked radiobuttons from the left and right div tag)
var rightValue = $("#right input[type='radio']:checked").val();
var leftValue = $("#left input[type='radio']:checked").val();

Related

AJAX and XML mutiple choice quiz - choices loading to same var

I'm having trouble getting the choices getting separated on different lines and I am not sure why and have not been able to figure out why
XML:
<q>
<qNum>1</qNum>
<qText>What is the side of a hammer called?</qText>
<choice>Hammer</choice>
<choice>Face</choice>
<choice>Side of the hammer</choice>
<choice>The check</choice>
</q>
AJAX:
$(document).ready(function(e) {
$.get('quiz.xml', function (d){
var html;
var title = $(d).find('title').text();
var desc = $(d).find('description').text();
html = '<div><h1>'+title+'</h1><br><h3>'+desc+'</h3><br></div>';
$('#1').append(html);
$(d).find('q').each(function(index, element) {
var $q = $(this);
var qNum = $q.find('qNum').text();
var qText = $q.find('qText').text();
var html2 = '<div><p>'+qText+'</p>';
$q.find('choice').each(function(index, element) {
var choice = $q.find('choice').text();
html2 += '<input type="radio" name="q'+qNum+'" class="choice" value="'+choice+'" /><label class="choice">'+choice+'</label><br>';
});
$('#1').append($(html2));
});
});
});
All the choices will be added to the var every time and i cant figure out how to break them up with keeping the same tag name
Please change it to
var choice = element.textContent;
You should change
var choice = $q.find('choice').text();
to
var choice = element.text();
I think. What it looks like is that for each choice, you select all the choices with $q.find('choice'), whereas you only want the choice you are currently iterating over, which is in element.

How to get multiple checkbox value and assign to hidden field

I want to store the multiple id to hidden field.
So value able to bind to controller.
<form:hidden id="ids" path="ids" value="${ids }"/>
When click button delete will call jquery to delete row.
var deleteIds = [];
$("#deleteRow").on('click', function() {
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
$('#ids').val(deleteIds);
});
My question is
How to set the value into ids?
Thank You.
The tag from doesn't have the attribute value. You can check the attributes for the form tag here.
However, you can use jQuery to modify custom attributes. Here's a working fiddle:
var deleteIds = [];
deleteIds = ["1","2","3","4"];
$('#ids').attr("value",deleteIds);
alert($('#ids').attr("value"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ids" path="ids" value="${ids }"/>
By creating multiple <form:hidden/>, you can get what you want. I assume you when you click #deleteRow, table rows is deleted and you submit form of these ids to server, so we can make it by follow.
Cause I even don't know your html structure, so I've just tried to modify your script, may help you;)
var deleteIds = [];
$("#deleteRow").on('click', function() {
$('#ids').remove();
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
for (var i = 0; i < deleteIds.length; i++) {
// formId should be replaced to your form id
$('#formId').append('<form:hidden id="ids" path="ids" value="' + deleteIds[i] +'"/>');
}
// $('#formId').submit(); comment this line, cause there is another button to submit form.
});
I able to set the multiples value to hidden field. Answer as below.
<form:hidden id="ids" path="ids" value="${ids }"/>
$("#deleteRow").on('click', function() {
var deleteIds = [];
$('.case:checkbox:checked').each(function(i){
if($('#ids').val() != ''){
deleteIds[i] = $('#ids').val() + "," + $(this).val();
}else{
deleteIds[i] = $(this).val();
}
});
$('#ids').attr("value",deleteIds);
});
The each(function(i)) will loop all the checkbox and store in array[], after that assign the array to hidden field.

Need text in input to not display user input once sent

Here is my jQuery, I have it working properly but once my row is added the user input in the inputs are still there and not cleared. How do I fix this?
// Removing menu rows
$('.menu-items').on('click', '.delete', function(){
$(this).closest('.menu-row').remove();
});
// HTML
var MENU_ROW_TEMPLATE = '<div class="menu-row"><span class="item-description">$description</span><div class="control-items"><span class="item-price">$price</span><span class="delete">X</span></div></div>'
// Adding menu rows
$('.menu-category').on('click', 'button', function(){
var $row = $(this).closest('.add-item');
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
var newRowHtml = MENU_ROW_TEMPLATE.replace('$description', name).replace('$price', price);
var $newRow = $(newRowHtml);
var $lastMenuRow = $row.closest('.menu-category').find('.menu-row').last();
$newRow.insertAfter($lastMenuRow);
});
Sorry for my poor explaining skills.
Clear the name and price after you get the values...
...
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
$row.find('input').first().val('');
$row.find('input').last().val('');
...

jQuery move table row's with inputs and change id/name

I need to have buttons for moving up and down table rows with input's inside.
On move I need to guarantee that the input's name's and id's are changed
regarding to their new position
I've tried around on JSFiddle but couldn't get it to work: http://jsfiddle.net/vaDkF/1194/
For example I've the first row is moved down there are four changes:
<input type="text" id="id_1" name="id_1"/>
<input type="text" id="test_1" name="test_1"/>
needs to become
<input type="text" id="id_2" name="id_2"/>
<input type="text" id="test_2" name="test_2"/>
but the values need's to stay the same just need the id/name to change.
This is just a test example, in production environment I have like 20 inputs
per row.
Hope someone can help.
Try this : after rearranging the rows, call a function which will reassigne id and name to the input fields
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
reAssignIdAndName();
});
reAssignIdAndName = function(){
$('table tr').each(function(index){
$(this).find('td:eq(2) input').each(function(){
//id of input element
var id = $(this).attr('id');
//get index of underscrore
var underScoreIndex = id.indexOf('_');
//take id till underscore and append your index+1 value
id = id.substring(0,underScoreIndex+1)+(parseInt(index)+1);
//assigne new id and name
$(this).attr('id',id);
$(this).attr('name',id);
});
});
};
});
Demo
This works and reAssign the position only for the 2 rows that moved :
jQuery(document).ready(function($){
$(".up,.down").click(function(){
var $this = $(this),
row = $this.parents("tr:first");
if ($this.is(".up")) {
if (row.parent().find("tr:first").get(0) !== row.get(0)) {
reAssignPosition(row.prev().find('input'));
row.insertBefore(row.prev());
reAssignPosition(row.find('input'), true);
}
} else {
if (row.parent().find("tr:last").get(0) !== row.get(0)) {
reAssignPosition(row.next().find('input'), true);
row.insertAfter(row.next());
reAssignPosition(row.find('input'));
}
}
});
function reAssignPosition($elt, up) {
var $row = $elt.parents("tr:first"),
oldPosition = parseInt($row.find('input').attr('id').replace(/(id|test)_/, '')),
newPosition, newId, newName, input = $row.find('input');
if (up) newPosition = oldPosition - 1;
else newPosition = oldPosition + 1;
$elt.each(function() {
this.id = this.id.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
this.name = this.name.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
});
}
});
Some refactoring can be done, I am sure, though.

Changing a div's id in order to show/hide

My old code looked like this:
function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
answer.className = "unhidden";
}
}
When my radio button was clicked:
<input class="editable" type="radio" name="q1" id="q1-a" onclick="unhide(this); scoreIncrement(this);"/>John
It would unhide this div:
<div id="answerq1a" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>
But now, my radio button must look like this:
<input class="editable" type="radio" name="q1" id="untitled-region-1" onclick="unhide(this); scoreIncrement(this);"/>John
and my div that I want to unhide has the same id, but as they are unique, it replaces the 1 with the next number up. In my case it is 4 id's down so the id would be "untitled-region-5" for the new id, as follows:
<div id="untitled-region-5" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>
So how can I change this code, to grab the new id "untitled-region-5" and minus 4 from it to fix it to the radio button with the new id's?
function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
answer.className = "unhidden";
}
}
I am going along this sort of track:
function unhide2(rad) {
var id = $("div").attr('id').replace(/untitled-region-/, 'untitled-region-');
var untitled-region = document.getElementById(id);
if (untitled-region) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
untitled-region.className = "unhidden";
}
}
But I don't know how to replace the last digit on the id with "digit-4".
You've tagged this with jQuery, so I'll give you the jQuery answer.
The right way to solve this is not to mash about with id's, but to link the radio, and it's associated div some other way, and IMO the best way is using a data- attribute.
<input class="editable" type="radio"
name="q1" id="q1-a" data-answerId="untitled-region-5"/>John
Then your javascript becomes easy-as:
$('.editable').click(function(){
$('#' + currentShown).removeClass('unhidden').addClass('hidden');
var answerId = $(this).data('answerId');
$('#' + answerId).removeClass('hidden').addClass('unhidden');
});
Although I urge you to do away with the unhidden, hidden confusion and just use .show() and .hide()!

Categories

Resources