Dynamic numbers of fields depending on values of another field - javascript

I have form and it look like this:
<div class="fieldWrapper">
<label for="id_rooms">Rooms:</label>
<input id="id_rooms" type="number" name="rooms" min="1">
</div>
<div class="extrafieldWrapper">
</div>
And I have script that add or delete couple of fields 'adult' and 'children' depending on value of field 'room'. Now i want to do the same thing with field 'children': depending on value of field 'children' script should add or delete fields 'children_age'. I tried to realize it something like this, but it isn't work.
$(function () {
$('#id_rooms').bind('blur keyup change', function () {
var n = $('#id_rooms').val() || 0;
$("input[id='id_form-TOTAL_FORMS']").attr('value', n);
$(".extrafieldWrapper").empty();
for (var i = 0; i < n; i++) {
$(".extrafieldWrapper").append("<br/><label for='id_form-" + i + "-adult'>Adult:</label> <input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/> <label for='id_form-" + i + "-children'>Children:</label> <input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children'/><div id='extrafieldWrapperChAge'></div>");
$("#id_form" + i + "children").bind('blur keyup change', function() {
var n = $("#id_form" + i + "children").val() || 0;
$(".extrafieldWrapperChAge").empty();
for (var i = 0; i < n; i++) {
$(".extrafieldWrapperChAge").append("<br/><label for='id_form-" + i + "-childrenage'></label><input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />");
}
});
}
});
});
I am newbie in java-script, can you tell me what i'm doing wrong. Thanks a lot.

Extract your inner code and use only one event handler for the childrens age field(s). In the code below I have added the class children_age to the input fields and then attached a event handler to listening for changes on all elements with that class.
Note 1: It should be enough to listen for change events.
Note 2: Use on instead of bind since it's recommended by the jQuery team
$(function(){
$('#id_rooms').on('change', function(e){
var n = $('#id_rooms').val() || 0;
var html = "";
for (var i = 0; i < n; i++) {
html += "<br/><label for='id_form-" + i + "-adult'>Adult:</label>"
+ "<input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/>"
+ "<label for='id_form-" + i + "-children'>Children:</label>"
+ "<input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children' class='children_age'/>"
+ "<div class='extrafieldWrapperChAge'></div>";
}
$(".extrafieldWrapper").html(html);
});
$(".extrafieldWrapper").on('change', '.children_age', function(e){
// $(this) refers to the element that changed
var n = $(this).val() || 0;
var html = "";
for (var i = 0; i < n; i++) {
html += "<br/><label for='id_form-" + i + "-childrenage'>Age of child "+(i+1)+"</label>"
+ "<input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />";
}
//.next - finds the next occurrence that matches the selector
$(this).next('.extrafieldWrapperChAge').html(html);
});
});

Related

jQuery Sum or Multiply values always without event trigger

Hi people i have a dynamic table (add rows from ajax requests) and i need sum and multiply values always (without a trigger event).
i have already a functions that make it with the event (blur) but i don't wanna make it by using the blur trigger.
There is a way for do it?
My code:
$.fn.sumValues = function() {
var sum = 0;
this.each(function() {
if ($(this).is(':input')) {
var val = $(this).val();
} else {
var val = $(this).text();
}
sum += parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
});
return sum;
};
function totaliza() {
var total_recep = $('input[name^="costot"]').sumValues();
$('#total_art').val(total_recep);
}
var counter = 0;
$(document).on('click', '#bt_add', function(e) {
counter++;
var tr = '<tr id="art_' + counter + '">';
tr = tr + '<td><button name="del_art' + counter + '" id="del_art' + counter + '" class="btn btn-default btn-xs del_art" type="button">DEL</button></td>';
tr = tr + '<td><input name="cbarra' + counter + '" id="cbarra' + counter + '" class="form-control" value="02020202" readonly></td>';
tr = tr + '<td><input name="art' + counter + '" id="art' + counter + '" class="form-control" value="ARTICULO" readonly></td>';
tr = tr + '<td><select name="und' + counter + '" id="und' + counter + '" class="form-control list"></select></td>';
tr = tr + '<td><input name="cal' + counter + '" id="cant' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="cal' + counter + '" id="costou' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="costot' + counter + '" id="costot' + counter + '" class="form-control cal" readonly value="0"></td>';
tr = tr + '</tr>';
$("#inv_recep_det tbody").append(tr);
$('.form-control').change(function() {
var number = this.name.replace('cal', '');
var costot = ($('#cant' + number).val() * $('#costou' + number).val())
$('input[name^="costot' + number + '"]').val(costot);
totaliza();
});
$('.del_art').click(function() {
var number = this.name.replace('del_art', '');
$('#art_' + number).remove();
totaliza();
});
});
https://jsfiddle.net/JuJoGuAl/kpLs9zcg/
Something like that?
http://jsfiddle.net/JuJoGuAl/0vx64u2y/
Rather than continuing in comments, I thought an answer might be of better use. Currently, you use:
$(".form-control).change(...)
to trigger the update. Some browsers may force you to lose the focus on an element to actually trigger that. Instead, change that line to:
$(".form-control").on("input", function(){ ... })
This has been discussed here: What is the difference between "change" and "input" event for an INPUT element
Other than that, I've made no changes to your fiddle: https://jsfiddle.net/snowMonkey/kpLs9zcg/5/

Display value from dynamic buttons in javascript

I'm trying to generate a series of buttons from a loop. On each button click, it should display the file.path of each button. The id is assigned dynamically from the loop itself. It is only displaying for the first one. here is the code:
Onclickling the button, it display the path for doc 1. But when clicking the second button, it display the path for doc1 too. It should display the path of doc 2
var result = {"data":"{\"files\":[{\"name\":\"doc1.pdf\",\"title\":\"networking\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc1.pdf\"},{\"name\":\"doc2.pdf\",\"title\":\"Armoogum\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc2.pdf\"}]}","isSuccessful":true};
var str= '';
var files = JSON.parse(result.data).files;
for(var file, i = 0; i < files.length; i++) {
file = files[i];
str += file.name + '<br />' + file.title + '<br/>' + '<input type="hidden" id="b" value="'+ file.path +'" />' + '<button onclick="add()">Add</button> '+ '<br/>' ;
}
alert(str);
$("#viewlist").html(str);
function add() {
var b = document.getElementById('b').value;
alert(b);
}
I will really appreciate it if i can get some help. Thank you.
All of your buttons have the same id, that is not going to work. There are a couple of ways of doing this. I modified your HTML slightly to group each section so you can easily find the associated hidden field for the button. I also passed in a reference to the button being clicked to the add function:
var result = {"data":"{\"files\":[{\"name\":\"doc1.pdf\",\"title\":\"networking\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc1.pdf\"},{\"name\":\"doc2.pdf\",\"title\":\"Armoogum\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc2.pdf\"}]}","isSuccessful":true};
var str= '';
var files = JSON.parse(result.data).files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
str += file.name + '<br /><div class="fileSection">' + file.title + '<br/>' + '<input class="fileName" type="hidden" id="b" value="'+ file.path +'" />' + '<button onclick="add(this)">Add</button> '+ '</div><br/>' ;
$("#viewlist").html(str);
function add(btn) {
var b = $(btn).closest('.fileSection').find('.fileName').val();
alert(b)
}
Where is str defined? I suspect it might be inside the for loop, but you want to make sure that you define it before the loop:
var str = '';
for(var file, i = 0; i < files.length; i++) {
file = files[i];
str += file.name + '<br />' + file.title + '<br/>' + '<input type="hidden" id="b" value="'+ file.path +'" />' + '<button onclick="add()">Add</button> '+ '<br/>' ;
}
I think the output is then what you are looking for.

Remove empty input field values, shown as dots in a table

Please can you help me with my code?
function tabelleFuellen(eingabeFeldArray) {
for (var eingabeFeldZaehler = 0; eingabeFeldZaehler < eingabeFeldArray.length; eingabeFeldZaehler++)
{
document.cookie += eingabeFeldArray[eingabeFeldZaehler].value + "|";
}
document.cookie += "~";
$('#tableinsert tbody').remove();
var zeilenArray = document.cookie.split('~');
for (var zeilenZaehler = 0; zeilenZaehler < zeilenArray.length - 1; zeilenZaehler++)
{
var spaltenArray = zeilenArray[zeilenZaehler].split('|');
document.getElementById("tableinsert").innerHTML += "<tbody><tr><td>" + spaltenArray[0] + "</td><td>" + spaltenArray[1] + "</td><td>" + spaltenArray[2] + "</td><td>" + spaltenArray[3] + "<td>" + spaltenArray[4] + "</td></tr></tbody>";
}
$('.field1').val('');
$(document).ready(function () {
var eingabeFeldArray = $('.field1');
tabelleFuellen(eingabeFeldArray);
});
}
This code takes value from input fields, saves them into a cookie and writes down into a table. But if the input fields are empty the table will always make a new row with a dot.
How to remove these dots?

Get variable from loop

I have a loop which is creating table:
for(m=1; m<7; m++){
document.getElementById('content').innerHTML +=
('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>')
}
In every row in second TD is button which must be assigned to every row. Each button has his own row. I want to alert m from the first TD exactly when i click button from that row. I mean if i will click button is switch2 i will get alert from m "2".
Here is the button code i tried:
var buttons = "#switch" + m
$(function() {
$(buttons).button();
$(buttons).click(function(){
alert(m);
});
});
This is not working because all of the buttons alerting last value from loop = 6.
I know it is confused but i hope you uderstand. Really appreciate your help
Change it to this:
$(function() {
var localM = m;
$(buttons).button();
$(buttons).click(function(){
alert(localM);
});
});
The problem is the alert binds to the variable m not the value of m. By allocating a local variable inside the closure you capture the value of m at that point in the loop.
you can also bind event another way, for sample
$("tr > td > input[type=checkbox]").function(e){
alert(event.target.id);
//OR
alert(this.id);
});
if you can add any class attribute in element
Then this is safe
$("tr > td > input[type=checkbox].switch").function(){
alert(event.target.id);
});
There is so many ways to do this. Here's one:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Populate Form
for (var m = 1; m <= 7; m++)
{
$('#content').append('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" class="clickMe" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>');
}
// Handle Click
$('.clickMe').click(function()
{
alert('You clicked on : ' + $(this).attr('id')); // alerts "switchN" e.g. switch1
// or //
alert('You clicked on : ' + $(this).attr('id').replace('switch', '')); // // alerts "N" e.g. 1
});
});
</script>
<table id="content"></table>
Here's a bit of a refactor (minus the button() plugin):
var $content = $('#content');
for (var m = 1; m < 7; m++) {
$content.append(
'<tr>' +
'<td>' + m + '</td>' +
'<td>' +
'<input type="checkbox" id="switch' + m + '">' +
'<label class="switch" data-num=' + m + ' for="switch' + m +'">Button ' + m + '</label>' +
'</td>' +
'</tr>'
);
}
$('label.switch').click(function(e) {
e.preventDefault();
alert($(this).data('num'));
});
JSFIDDLE

how to select only one radio button at a time having different name using jquery?

html code:
<div id="localPropList"></div>
<div id="assignedPropList"> </div>
js code:
function getLocalProposals()
{ // filling these radio buttons dynamically
var htmlStringLocalPro = '<fieldset id="local_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var k = 0; k < result.rows.length; k++) {
var localProposal = result.rows.item(k);
if( !(jQuery.inArray( localProposal.id, arrForQueuePropId ) >=0 ) )
{var fieldId = 'localPro' + k;
htmlStringLocalPro += '<input group="1" type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + localProposal.enquiry_no + ',' + localProposal.id + '"/>'
+ '<label for="' + fieldId + '" data-iconpos="right">' + localProposal.enquiry_no+'-'+localProposal.caller_name+'</label>';
}
htmlStringLocalPro += '</fieldset>';
}
function getAssignedproposals()
{
var htmlString = '<fieldset id="assigned_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var i = 0;i < obj.Proposal.length; i++) {
proposalIds += obj.Proposal[i].id + ',';
if( !(jQuery.inArray( obj.Proposal[i].id, arrForQueuePropId ) >=0 ) ){
var fieldId = 'ap' + i;
htmlString += '<input group="1" type="radio" name="assigned_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
// htmlString += '<input type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
}
}
htmlString += '</fieldset>';}
$("input:radio[name=local_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
$("input:radio[name=queue_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
i need to select only one radio button at a time if radiobutton having name="assigned_proposal_id" is selected then it should not allow to select any radio buttons for name="local_proposal_id]" i cannot assign id different i need to do selection on the basis of name and i cant assign same name to separate group as well
please tell me whats the solution
Checking / Unchecking in jQuery Mobile, you need to use .prop to checked or unchecked and then call .checkboxradio('refresh').
Demo
$(document).on('pageinit', function () {
$(document).on('change', '[type=radio]', function (e) {
// Uncheck radio buttons in #group1 and #group2
$('#group1 [type=radio]:checked, #group2 [type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// "OR" to select all radio buttons in DOM
$('[type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// Check clicked radio
$(this).prop('checked', true).checkboxradio('refresh');
});
});
try the following
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
$('input [name="assigned_proposal_id"]').click(function(){
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
});
It will work like what hussain told
Here A FIDDLE for your purpose. It will uncheck all the radio button, then check the one we clicked on.
HTML :
<div id="localPropList">
<input name="assigned_proposal_id" type="radio" value="value1-1" />value1-1
<input name="assigned_proposal_id" type="radio" value="value1-2" />value1-2
<input name="assigned_proposal_id" type="radio" value="value1-3" />value1-3
</div>
<br/>
<div id="assignedPropList">
<input name="local_proposal_id" type="radio" value="value2-1" />value2-1
<input name="local_proposal_id" type="radio" value="value2-2" />value2-2
<input name="local_proposal_id" type="radio" value="value2-3" />value2-3
</div>
div selected : <span></span>
JQUERY :
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').change(function(){
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').prop('checked', false);
$(this).prop('checked', true);
$('span').html($(this).val());
});
Disable Syntax:
$('input[name="name_here"]').attr('disabled', 'disabled');
Don't go for the hardest thing
Hussein Nazzal is correct but space matters
between input and '[' bracket
if($('input[name="assigned_proposal_id"]:checked').val() != '')
{
$('input[name="local_proposal_id"]:radio').attr('disabled', 'disabled');
}
Demo
This worked for me, take into account that according to the selector this change will apply to all RadioButtons in the document with the same class, in this case class="chartIndex":
$(".chartIndex").change(function () {
$('[type=radio]:checked').prop('checked', false);
$(this).prop('checked', 'checked');
});
Hope this helps someone. Regards.

Categories

Resources