Dynamically created form from database and accessing elements with jquery - javascript

I have form that is created from database. Form contains radio buttons which are created like this
<label>
<input type="radio" name="rizici_radio<?php echo $riz_id ?>"
value="<?php echo $rizik['riz_vrednost_da']; ?>" >
<?php echo $rizik['riz_vrednost_da']; ?>
</label>
Name attribute contains rizici_radio and id from database. And every row has pair of radio buttons with values 1 or 0.
So my problem is manipulating changing values of that pair of radio buttons. For example when i select radio button with value 1 it should fill span tag with value of changed radio button. And i have another span where sum of values from all span tags should be displayed.
Grey is span where value of selected radio button should be stored

Using loop might create issue as some times loop counter value and DB ID's might differ. So what you need to do set DB ID to both radio button set like below where i am setting rel-id value to DB Ids
<label><input type="radio" class="promena" rel-id = '2' name="rizici_radio2" value="1" >1</label>
<label><input type="radio" class="promena" checked rel-id = '2' name="rizici_radio2" value="0">0</label>
And use below jquery code
$(".promena").on("change",function(){ // bind a function to the change event
if( $(this).is(":checked") ){ // check if the radio is checked
var val = $(this).val(); // retrieve the value
var id = $(this).attr("rel-id");
$("#bodovi"+id).val(val); //setting value to respective hidden field
$("#scores"+id).text(val); // showing selected radio button value in gray area
}
});
Hope this helps you.

with jQuery:
$(radiobutton selector here).click(function(){
$(this).next(".greyValueArea").val($(this).val());
})
This should do the trick. just change selectors.
"Selectors i must create from id's. That is my main problem. I must use something like for loop to add id to either name or id"
#Thug you can also give them some class that they would be having incommon.
You see: If you make a
$('.button').on("click",function(){
console.log($this)
})
It will console log button class item you clicked and it applies to every button class you have

First of all, I think it would be better to request the table data with an ajax request as json data from server if you need to update the server data later.
Anyway, for getting the clicked row you can also use the following script:
$('.selectionForm').on('change', 'input[type="radio"]',
function(event) {
console.log('changed radio', $(this).attr('name'), $(this).val(), $(this).parent().find('span'));
$(this).parent().find('span').text($(this).val());
});
It goes up in the DOM to the parent of the clicked radio button and then with find you're going down again to the span of that row.
It uses event delegation because that's required for dynamically added content from the ajax request. That would be not required for the PHP added content.
Please see the demo below and here at jsfiddle.
Handlebars.registerHelper('isChecked', function(input, options) {
//console.log(input, this);
//console.log(this, this.value, input);
return this.value === input? 'checked': '';
});
var $out = $('#out'),
rowTmpl = $("#row-template").html(),
template = Handlebars.compile(rowTmpl);
$.ajax({
url: 'http://www.mocky.io/v2/556d9fd9e822500114253f39',
jsonp: 'callback',
dataType: "jsonp",
success: function(response) {
console.log(response);
$.each(response, function(index, data) {
//console.log(data);
$out.append(template(data));
});
}
});
$('.selectionForm').on('change', 'input[type="radio"]', function(event) {
console.log('changed radio', $(this).attr('name'), $(this).val(), $(this).parent().find('span'));
$(this).parent().find('span').text($(this).val());
});
//$out.html(JSON.stringify(dataArray));
ul {
list-style-type: none;
}
li {
border-bottom: 1px solid gray;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>form loaded with ajax request:</h1>
<p>table generated with javascript</p>
<form class="selectionForm">
<ul id="out"></ul>
<!--<ul>
<li>
<input type="radio" name="row0" value="0"/>0
<input type="radio" checked="" name="row0" value="1"/>1
<span class="badge">1</span>
</li>
<li>
<input type="radio" name="row1" value="0"/>0
<input type="radio" checked="" name="row1" value="1"/>1
<span class="badge">1</span>
</li>
</ul>-->
</form>
<script id="row-template" type="text/x-handlebars-template">
<li>
<input type="radio" value="0" name="row{{id}}" {{isChecked 0 }}/>0
<input type="radio" value="1" name="row{{id}}" {{isChecked 1 }}/>1
<span class="badge">{{value}}</span>
</li>
</script>
<h1>form generated with server side script</h1>
<form class="selectionForm">
<ul>
<li>
<input type="radio" name="row0" value="0"/>0
<input type="radio" checked="" name="row0" value="1"/>1
<span class="badge">1</span>
</li>
<li>
<input type="radio" name="row1" value="0"/>0
<input type="radio" checked="" name="row1" value="1"/>1
<span class="badge">1</span>
</li>
</ul>
</form>

Related

How to remove a part of the content of a div with jQuery?

When I click on a checkbox, I append some content to a div (#item_list)
if(cb_new.prop('checked')) {
$("#item_list").append("<input type='hidden' name='post[]' value="+ this.value +">");
} else {
// ??
}
When I uncheck the box I want that exact same string to be removed from the div. Keeping all the others that have a different value (this.value).
So for example I could have:
<div id="item_list">
<input type="hidden" name="post[]" value="102">
<input type="hidden" name="post[]" value="93">
</div>
But if I uncheck
<input type="checkbox" id="d-102-2" name="d-102" value="102" data-id="d-102">
I want :
<div id="item_list">
<input type="hidden" name="post[]" value="93">
</div>
If I check it again, I want it back.
How can I do that?
A vanilla JS solution would look like:
Updated according to your expanded requirements.
document.querySelector(`#item_list input[value='${this.value}']`).remove();
This will query the DOM, find an input element, with a value attribute whose value is equal to this.value, and remove it from the DOM with the remove() method.
A more detailed implementation isn't easy to give without having more information.
You can use the data attribute to assign unique id to the checkbox, once it is checked, input element with same data-uid is added and once unchecked we remove the input element with same data-uid
$(document).ready(function() {
$("#cb_new").change(function() {
if ($(this).prop('checked')) {
$("#item_list").append($("<input data-uid='"+$(this).data('uid')+"' type='text' name='post[]' class='newItem' value='" + $(this).val() + "'>"));
} else {
$('.newItem[data-uid='+$(this).data('uid')+']').remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="cb_new" data-uid="8080" value="tick Me" name="test"/><label for="test">Tick Me</label>
<div id="item_list" style="border:1px solid tomato">
</div>

Dynamic Checkbox selector in jquery

I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)
ModellingTagID_1201
ModellingTagID_1202
ModellingTagID_1203
ModellingTagID_1204
I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?
$jqLib("#ModellingTagID_*").change(function(){
var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
$jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
});
you can apply same class to all those checkboxes
<li><input type="checkbox" id="yourcbid1" name="x" value="1" class="yourcbclass" /> cb1</li>
<li><input type="checkbox" id="yourcbid2" name="x" value="1" class="yourcbclass" /> cb2</li>
and then you can make function for it's change event like this.
$(function(){
$('.yourcbclass').on('change', function() {
if($(this).is(':checked'))
{
//do your stuff here
}
});
});
see if this helps..
Very simple using this way:--
$("#envoyer").click(function(e) {
var myArray = [];
$(":checkbox:checked").each(function() {
myArray.push(this.value);
});
if(myArray == ''){
alert('Please check');
}else{
alert("Checked: " + myArray.join(","));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
one<input type="checkbox" name='checkbox0' value="one_name" checked>
two<input type="checkbox" name='checkbox1' value="one_name1">
three<input type="checkbox" name='checkbox2' value="one_name2">
<input type="button" id="envoyer" value="Envoyer Reponse" />
</body>
</html>
From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.
cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">
And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.
$(document).ready(function(){
$('.someclass').on('change', function() {
alert($(this).attr("id"));
});
});

Removing from array values of checkboxes in jQuery

I have a checkboxes like this:
while($userRow=$resultForUsers->fetch_assoc()){
$nameOfUser=$userRow['users_name'];
$userId=$userRow['user_facebook_id'];
$userFBPicture=$userRow['users_picture'];
echo "
<tr class='tr-data-users'>
<td class='text-center'>
<input type='checkbox' class='checkbox' onclick='if(this.checked){selo(this.value)}else{izbaci(this.value)}' value=$userId>
</td>
So, for each user in my database I'm having one checkbox with value of his id. I need id's of all checked users(i.e checkboxes) in one array. I did it this way:
<input type='checkbox' class='checkbox' onclick='if(this.checked){put(this.value)}else{remove(this.value)}' value=$userId>
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
}
So, console.log now displays id's of all checked checkboxes. What I want to do is if checkbox is unchecked then to remove that id(i.e chechbox value) from array. I tried it like this:
onclick='if(this.checked){put(this.value)}else{remove(this.value)}'
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
remove(o,niz);
}
function remove(o,niz){
if($.inArray(o,niz)){
console.log('radim');
var indexNiza= $.inArray(o,niz);
niz= $.grep(niz,function(a,o){
return (a!=o);
});
}
}
As you can see this else part should handle if checkbox is unchecked and remove that id from array, but it doesn't work. Would really appreciate help on this.
It seems that the code you have written is taking a very complex route for a simple job. You can see the following for a good example on how to obtain all of the values into their own arrays for the checked and unchecked states.
In the demonstration, I enumerate through the checked and unchecked checkboxes if the user changes the state of any checkbox, and store the checked values in an array named cbChecked and the unchecked values get stored in cbUnchecked
The key here is the selectors used:
Selector usage
Get all 'checked' objects
:checked
Get all 'unchecked' objects
:not(:checked)
Demonstration
$(document).ready(function() {
$("input[type='checkbox']").change(function() {
var cbChecked = new Array();
var cbUnchecked = new Array();
$("input[type='checkbox']:checked").each(function() {
cbChecked[cbChecked.length] = this.value;
});
$("input[type='checkbox']:not(:checked)").each(function() {
cbUnchecked[cbUnchecked.length] = this.value;
});
$("p#cbChecked").html( cbChecked.join() );
$("p#cbUnchecked").html( cbUnchecked.join() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> The checkbox form</h2>
<form id="foo">
<p>A : <input type="checkbox" id="a" value="a"></p>
<p>B : <input type="checkbox" id="b" value="b"></p>
<p>C : <input type="checkbox" id="c" value="c"></p>
<p>D : <input type="checkbox" id="d" value="d"></p>
<p>E : <input type="checkbox" id="e" value="e"></p>
<p>F : <input type="checkbox" id="f" value="f"></p>
</form>
<h2>Checked Values</h2>
<p id="cbChecked"></p>
<h2>Unchecked Values</h2>
<p id="cbUnchecked"></p>

How to change part of url (ID) using radio button?

I got some radio buttons pushed by a loop in JSP:
<input type="radio" name="radioBtn" value="<s:property value="#country.getIdCountry()"/>">
The value of the radio button describe the ID of a country it selects.
Then I created some links eg.:
<a href='addDefaultPoints.action?countryId=<s:property value="#country.getIdCountry()"/>&height=400&width=350'>Link 1</a>
<a href='editCountryMap.action?height=550&width=750&id=<s:property value="#country.getIdCountry()"/>&keepThis=true&TB_iframe=true'>Link 2</a>
I would like to change code into some dynamic page, that can change the ID on the onChange event of the radio button set, within an url specified in href.
I tried using Javascript for this functionality, but with no luck. Perhaps I need to do this on the server side. I am using JSP, struts, Jquery and Javascript.
Here is what I tried:
var myGetValue = parseURL("id");
function checkV(f,v){
for(var i=0;i<c.length;i++){
c[i].checked=(c[i].value==v)?true:false;
}
}
checkV(myForm,myGetValue);
You can write below logic :
create url in hidden input with some constant name for county id, use same class name for corresponding anchor tag
<input class="COUNTY_ID" type="hidden" value="addDefaultPoints.action?countryId=COUNTY_ID&height=400&width=350">
<a class="COUNTY_ID" href="#"/>
write change event for radio button :
$('input[name="radioBtn"]').change(function(){
var radioVal = $(this).val();
var url = $('input[class="COUNTY_ID"]').val();
url = url.replace('COUNTY_ID',radioVal);
$('a[class="COUNTY_ID"]').attr('href',url);
});
Use similar logic for other links also ...
HTML
<input type="radio" name="radioBtn" value="1">
<input type="radio" name="radioBtn" value="2" checked>
<input type="radio" name="radioBtn" value="3">
<input type="radio" name="radioBtn" value="4">
<a id="lnk1" href='addDefaultPoints.action?height=400&width=350&countryId='>Link 1</a>
<a id="lnk2" href='editCountryMap.action?height=550&width=750&keepThis=true&TB_iframe=true&id='>Link 2</a>
JS
$(document).ready(function() {
var countryId = $('input[name=radioBtn]:checked').val();
$('a#lnk1').attr('href', $('a#lnk1').attr('href') + countryId);
$('a#lnk2').attr('href', $('a#lnk2').attr('href') + countryId);
});
Explanation
First you get the selected country by checking the checked radiobutton of the group radioBtn.
Then you make sure that the country param of your url is at the end so that you can concatenate the countryId to the rest of your links attribute 'href'.
Result
Link1: addDefaultPoints.action?height=400&width=350&countryId=2
Link2: editCountryMap.action?height=550&width=750&keepThis=true&TB_iframe=true&id=2
If the param is not ad the end of the link then you can use the replace() function like Bhushan Kawadkar mentioned.

How to rename a html form elements' Id attribute using Jquery?

I have a form which contains radio boxes.
<input type="radio" name="categoryid" id="category420" value="420" onclick="checkCategory();" > Category1
<input type="radio" name="categoryid" id="category1314" value="13,14" onclick="checkCategory();" >Category2
<input type="radio" name="categoryid" id="category594" value="594" onclick="checkCategory();" >Category3
When the radio elements value attribute is a comma separated list (13,14) I need the elements Id attribute to change.
In the example above, when the second category is selected then "CategoryIDs=13,14" should be passed to the action page not categoryid. But for the other two categories it should pass categoryid value.
I cannot edit the action page.
The question: How can I change the radio buttons Id attribute in JQuery?
Change the Id
Based on your requirement to have only one Id (categoryid/s) then you could change the Id using JQuery, before the form is submitted.
JSFiddle working example - http://jsfiddle.net/daTYY/
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$(this).attr("id","newId");
}
});
});
Update a hidden input
Add a hidden input named categoryids. Then use JQuery to check if categoryid contains a comma and if it does populate categoryids with the value.
JSFiddle working example - http://jsfiddle.net/KVs79/
HTML
<input type="radio" name="categoryid" id="categoryid1" value="13,14" />Category2
<input type="radio" name="categoryid" id="categoryid2" value="404" />Category3
<input type="hidden" name="categoryids" id="categoryids" value="" />
JQuery
$(function() {
$('input:radio[name=categoryid]').change(function() {
if ($(this).val().indexOf(",") >= 0) {
$("#categoryids").val("13,14");
}else{
$("#categoryids").val("");
}
});
});

Categories

Resources