Finding closest input to select in dynamically generated code - javascript

So what I'm trying to do is change value of input with id championSpell[] whenever something from dropdown is chosen this code is generated dynamically so I'm always trying to get the closest/next input after select.
UPDATE: Full code below:
<script src="LeagueNotes/js/jquery.min.js"></script>
<script src="LeagueNotes/js/champions_list.js"></script>
<script src="LeagueNotes/js/jquery.validate.min.js"></script>
<style>
* { font-family:Arial; }
h2 { padding:0 0 5px 5px; }
h2 a { color: #224f99; }
a { color:#999; text-decoration: none; }
a:hover { color:#802727; }
p { padding:0 0 5px 0; }
input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }
</style>
<h2>
Add Another Champion
</h2>
<form name="second_form" id="second_form" action="#" method="POST" style="margin: 0;" >
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="champion[]" size="20" list="champions" value="" placeholder="Enter Champion's name">
<datalist id="champions"></datalist>
Add General Change<a></a>
Add Spell<a></a>
</label>
</p>
</div>
<br/><input type="submit" value="submit">
</form>
<script>
for(var key in champions){
if(champions.hasOwnProperty(key)){
$('#champions').append('<option value="' + key + '">');
}
}
var config = {
fillAll: true
};
document.forms["second_form"].oninput = function(e) {
var champion = this["champion[]"];
//Force into array
if (champion[0] === undefined)
champion = [this["champion[]"]];
var reached = {
valid: 0,
unique: 0
};
var inputs = [].map.call(champion, function(n) {
return n.value
}).filter(function(n) {
return n.length
});
var valid = [].every.call(champion, function(n, i) {
n.setCustomValidity("");
if (config.fillAll) return (reached.valid = i, champions.hasOwnProperty(n.value));
else return n.value ? (
reached.valid = i,
champions.hasOwnProperty(n.value) > -1
) : true;
});
var unique = inputs.slice(0).sort().every(function(n, i, a) {
reached.unique = inputs.lastIndexOf(n);
return n != a[i - 1];
});
//Check for valid champions
if (!valid) {
champion[reached.valid].setCustomValidity("This is not a valid champion, please correct this field and resubmit.")
}
//Check for duplicates
if (!unique) {
champion[reached.unique].setCustomValidity("This champion has already been entered.")
}
this.checkValidity();
};
function change(x, dblchamp){
if(dblchamp===true){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="Q2"){x=2;}
if(x==="W"){x=3;}
if(x==="W2"){x=4;}
if(x==="E"){x=5;}
if(x==="E2"){x=6;}
if(x==="R"){x=7;}
if(x==="R2"){x=8;}
}else if(dblchamp===false){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="W"){x=2;}
if(x==="E"){x=3;}
if(x==="R"){x=4;}
}
console.log(x);
return x;
}
function val(elm) {
var championsWithExtraSpells = ["Aatrox", "Elise", "Fizz", "Heimerdinger", "Jayce", "Lee Sin", "Nidalee", "Rek'Sai","Twisted Fate"];
//var championName = $("#change").closest('input').val();
//var championName =$("#champion\\[\\]").val();
var championName = $(elm).closest("label").find("input").val();
//document.getElementById("champion[]").value;
console.log(championName);
if($.inArray(championName, championsWithExtraSpells)==-1){
var existsInArray = false;}
else{
var existsInArray = true;}
var d = $(elm).val();
// console.log(d);
//d = document.getElementById("change[]").value;
var spellname = document.getElementById("championSpell[]");
var z = champions[""+championName+""][change(d, existsInArray)];
test = $(elm).nextAll("input").first().val('test');
console.log(test);
//console.log(d+spellname);
//test.value=champions[""+championName+""][change(d, existsInArray)];
}
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents label').size() + 1;
var j =0;
$('body').on('click', '#addChampion', function() {
$('<p>Remove<br><label for="p_scnts"><input type="text" id="champion[]" size="20" list="champions" name="champion[]" value="" placeholder="Enter Champion\'s name" /><datalist id="champions"></datalist>Add General Change Add Spell<a></a></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('body').on('click', '#remScnt', function() {
if( i >2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('body').on('click', '#addGeneral',function() {
$(
'<p><label for="var"><textarea type="text" id="champion[]" size="20" name="GeneralChange[]" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Remove Change</p>').appendTo($(this).next());
j++;
return false;
});
$('body').on('click', '#remVar',function() {
$(this).parent('p').remove();
return false;
});
$('body').on('click', '#addSpell',function() {
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Add Change Remove Spell</p>').appendTo($(this).next());
return false;
});
});
</script>

It is be next sibling of the select, so use .next(), .closest() is used for finding the first ancestor element matching the given selector
function val(elm) {
var test = $(elm).next("input");
console.log(test);
test.val("test: " + elm.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="change[]" id="change[]" onchange="val(this)">
<option value="Passive">Passive</option>
<option value="Q" selected>Q</option>
<option value="W">W</option>
<option value="E">E</option>
<option value="R">R</option>
</select>
<input type="text" id="championSpell[]" readOnly="true">
But it is better to use jQuery event handlers
jQuery(function() {
$('select[name="change[]"]').change(function() {
$(this).next().val('t: ' + this.value);
}).change(); //the last change value is used to set the initial value on page load
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="change[]" id="change[]" onchange="val(this)">
<option value="Passive">Passive</option>
<option value="Q" selected>Q</option>
<option value="W">W</option>
<option value="E">E</option>
<option value="R">R</option>
</select>
<input type="text" id="championSpell[]" readOnly="true">

Use .next() .
var test = $(elm).next("input").val('test');
your code
function val(elm) {
var test = $(elm).next("input").val('test');
}

This one depends on how robust to changes in the DOM you want to be.
If you may have elements in between, the best option is
$(elm).nextAll("input").first().val('test');
nextAll() returns all following siblings of the element, used with "input" will return all following inputs only. Then apply first().
If that hierarchy may change, you would go up the DOM to a closest container with both elements, then search down again.
e.g. if these were in two standard <div class="form-group"> containers (ala a Bootstrap form):
$(elm).closest(".form-group").next(".form-group").find("input").first().val('test');
Update:
You should avoid inline event handlers with jQuery. They do not support all the same features jQuery handlers do and separate the event registration from the event handler for no good reason.
A practical example is here http://jsfiddle.net/TrueBlueAussie/mo94pv8k/
$('select').change(function () {
$(this).nextAll("input").first().val($(this).val());
});
Notes:
Your current ids are not useful for jQuery use as [] is reserved to indicate attribute selection in a jQuery selector. For example $('#change[]') is an invalid selector.

Related

Checkbox select deselect all and perform function

I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine. What I would like to do is have the checkboxes perform their functions when select all is clicked. It works at the moment, but only when I refresh the page. I would like it to happen when select all is clicked.
Here's what I've been playing with so far:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
this.click();
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 1
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 2
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 3
</label>
<button type="button" class="js-button">Check/uncheck all</button>
<div class="js-result"></div>
JSFiddle
CheckBox should be handled with onchange event.
Below code I am firing an event whenever the checkbox checked programmatically.
Below code may help you
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
/* this.click(); */
this.fireevent('onChange');
/* or you can call this.onChange(); */
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
In case you are using only java script.
Below is the very simple running example. which consumes short time without any use of external library as JQuery
HTML code
<html>
<head>
<title>test</title>
<script>
function amend(a)
{
document.getElementById("ta").value += a;
}
function checkAll()
{
var textboxes = document.getElementsByClassName("cb");
for(i=0;i<textboxes.length;i++)
{
textboxes[i].checked=true;
textboxes[i].onchange();
}
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="ta">
Below the outputs
</textarea>
<div id="checkdiv">
<input type="checkbox" onChange="amend(this.value)" value="data to add 1" class="cb">First</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 2" class="cb">Second</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 3" class="cb">Third</input>
<br>
<input type="checkbox" onChange="checkAll()">Check all</input>
</div>
</body>
</html>

change the Input Name based on the multiple dropdown selection in html form?

I am trying to create add/remove form fields dynamically with jQuery where the user can submit multiple queries based on the dropdown selections. At the end, it should generate URL with a combination of selection.So far I have managed to create add/remove form fields with the option of multiple queries.
For example, if the user submits input for a car then it will generate URL like:
exmaple.com/?car=xxx
and which is working.
If a user submits input for car and bike then it should generate:
exmaple.com/?car=xxx&bike=yyy
but it is generating like:
exmaple.com/?car=xxx&car=yyy
So how can I solve this issue? Thank you in advance.
$(function() {
$.fn.addmore = function(options) {
var moreElement = this,
singlePreSelectedValue = '',
selectedValue = [],
defaultOption = {
addText: 'add more',
removeText: 'Remote',
selectBoxDuplicate: true,
avoidDuplicationSelection: function(e) {
var o = e;
if ($.inArray($(o).val(), selectedValue) != -1) {
$(o).val(singlePreSelectedValue);
alert('Value already selected.');
} else {
var hasSelectValue = true;
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() == 'select') {
hasSelectValue = false;
return false;
}
});
}
},
prevSelectedValue: function(e) {
var o = e;
selectedValue = [];
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
selectedValue.push($(this).val());
}
});
singlePreSelectedValue = $(o).val();
}
}
defaultOption = $.extend(true, defaultOption, options);
/* $(this).find('select').prepend('<option value="select" selected>Select</option>');*/
$(moreElement).after('' + defaultOption.addText + '');
$('[data-id="more"]').click(function() {
var dataMore = this,
removeDuplication = [];
$(dataMore).before($(moreElement).clone().find('input').not('input[type="submit"]').val('').end().end().find('select.removeDuplication').focus(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.prevSelectedValue(this);
}
}).change(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.avoidDuplicationSelection(this);
}
}).end().append(function() {
return $('<i class="fa fa-trash"></i> ' + +'').click(function() {
$(this).parent().remove();
});
}));
if (!defaultOption.selectBoxDuplicate) {
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
removeDuplication.push($(this).val());
}
});
$.each(removeDuplication, function(i, v) {
$('.removeDuplication').last().find('option[value="' + removeDuplication[i] + '"]').remove();
});
}
});
$('.removeDuplication').focus(function(e) {
defaultOption.prevSelectedValue(this);
}).change(function() {
defaultOption.avoidDuplicationSelection(this);
});
return this;
}
$('dl').addmore({
addText: 'Add',
removeText: 'Remove',
selectBoxDuplicate: false
});
});
$(document).ready(function() {
$("select").change(function() {
var str = $(this).val();
$("#searchtermid").attr("name", str);
});
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="navbar-form" action="" method="get" action="demo_form.asp">
<dl>
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</dl>
<input class="btn btn-primary" type="submit" value="Submit">
</form>
After getting input from Standard Quality, I have modified my scripts and html.
https://jsfiddle.net/paul85/wjhqszmg/
But still is not letting the user submit input form. Most important, when user will submit from it should redirect to a page for correctly generated URL.
If user submit input for car and bike then redirecting page address or URL will be:
exmaple.com/?car=xxx&bike=yyy
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="/results.html" method="get">
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication">
<option value="car" >Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>
</div>
</div>
<button class="add_field_button">Add More Fields</button>
<input class ="btn btn-primary" type="submit" value="Submit" >
</form>
JAVASCRIPT
$(document).ready(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication">\
<option value=""></option>\
<option value="car">Car</option>\
<option value="bike">Bike</option>\
<option value="plane">Plane</option>\
</select>\
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).val()+' already selected.');
}
});
});
/*$(form).submit(function(e){*/
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
if (query.type !=""){
queries.push(query);
} else{
slectedall=false;
}
});
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
if (query.value.trim() ===""){
fillupfield=false;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Please insert your searchterm.');
} else {
$("form").submit();
}
}
});
});
It looks like you're extending jQuery, which isn't necessary for this, and is contributing to making the code much less legible. To be honest, I haven't even dug through it to find the problem -- instead, I wrote something from scratch. StackOverflow snippets don't allow forms, so here's a working JSBin: http://jsbin.com/gokodaluna/edit?html,js,output
(Note that I've changed your HTML markup a little bit)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="" method="get" action="demo_form.asp">
<div class="fields">
<div class="form-field">
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<h2 id="final-url"></h2>
</body>
</html>
Javascript:
/* Save your initial variables */
var form = $('#main-form');
var formFields = form.find('.fields')
var addButton = $('#form-add');
var emptyInput = $('.form-field').clone(); // clone this at initialization so we always have an empty field
var finalUrl = $("#final-url");
addButton.on('click', function() {
emptyInput.clone().appendTo(formFields);
/* clone this again so our initial field is always empty and available */
})
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
queries.push(query);
});
var url = window.location.href;
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
url += ampOrQ + query.type + "=" + query.value;
}
/* print the URL into the dom if you want to see it working */
finalUrl.text(url);
/* or forward users to the new URL you've generated */
window.location.href = url;
})
Edit: in the revised code in your question, you're calling $("form").submit() in that if-else statement. When you trigger this, the larger function is still catching the submit event, so it's immediately running e.preventDefault() again. If you need to simply forward the user to the new URL, just set it with window.location.href =. See the last few lines of my (edited) code above.

Not working select option dynamic field in jquery

jQuery(function() {
var currentCount = 0;
jQuery('#addMoreEmail').click(function() {
currentCount = cloning('#MoreEmailDetails', '#MoreEmails', currentCount);
return false;
});
function cloning(from, to, counter) {
var clone = $(from).clone();
//console.log(clone);
counter++;
// Replace the input attributes:
clone.find(':input').each(function() {
var name = jQuery(this).attr('name').replace(0, counter);
var id = jQuery(this).attr('id').replace(0, counter);
jQuery(this).attr({
'name': name,
'id': id
}).val();
});
// Replace the label for attribute:
clone.find('label').each(function() {
var newFor = jQuery(this).attr('for').replace(0, counter);
jQuery(this).attr('for', newFor);
});
// Replace the text between html tags:
clone = clone.html().replace(1, counter);
jQuery(to).before(clone);
return counter;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MoreEmailDetails">
<div class="form-group users">
<input type="text" required="required" id="LeadEmailDetail0FirstName" value="" name="data[LeadEmailDetail][0][first_name]">
<label for="LeadEmailDetail0FirstName">First Name</label>
<input type="text" id="LeadEmailDetail0LastName" value="" name="data[LeadEmailDetail][0][last_name]">
<label for="LeadEmailDetail0FirstName">First Name</label>
<select id="LeadEmailDetail0CountryId" class="select-replace select2-offscreen" name="data[LeadEmailDetail][0][country_id]" tabindex="-1" title="Country">
<option value="">Choose a country</option>
<option value="2">SOUTHEASTERN EUROPE</option>
</select>
<label for="LeadEmailDetail0CountryId">Country</label>
<input type="checkbox" id="LeadEmailDetail0PrimaryEmail" value="1" name="data[LeadEmailDetail][0][primary_email]">
<label for="LeadEmailDetail0PrimaryEmail">Primary Email</label>
</div ">
</div">
<div id="MoreEmails"></div>
<input type="submit" value="Add More" id="addMoreEmail">
In above code input type text and checkbox working fine (adding dynamic fields after click add more) but i m getting below error in case select option
TypeError: jQuery(...).attr(...) is undefined
You need to add a null check for jQuery(this).attr('name')) . JSFIDDLE
Following is the modified JS code block.
clone.find(':input').each(function() {
if(jQuery(this).attr('name')) {
var name = jQuery(this).attr('name').replace(0, counter);
var id = jQuery(this).attr('id').replace(0, counter);
jQuery(this).attr({
'name': name,
'id': id
}).val(); }
});

Input Field is not enabled after changing Select option

I have created a stand alone code for enabling/disabling input field and it is working perfectly .
HTML:
Identification Type:
<select name="Identification-Type" id="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="23434">--sfgdg--</option>
<option value="135111">--dfgb--</option>
<option value="1165611">--gdg--</option>
<option value="114511">--vcbc--</option>
</select>
<!-- <input type="checkbox" class="Identification-Number" value="Identification-Number"
name="Identification-number" id="Identification-Number"> -->
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number" id="Identification-Number">
JS:
$('select[name="Identification-Type"]').change(function () {
var $this = $('#Identification-Number');
$this.attr("disabled", false);
$this.attr("disabled", ($(this).val() == '1111') ? true : false);
}).trigger('change');
JSFIDDLE LINK
But,when I tried to incorporate this logic in another form, it is not working .
HTML:
<form name="pancettaForm" method="post" action="demor" id="pancettaForm">
<ul>
<li>
<label for="PartyChoose">Choose Appropriate Party:</label>
</li>
<br>
<input id="person" name="PartyChoose" type="radio" value="update-person" class="required" />Person
<br />
<input id="organization" name="PartyChoose" type="radio" value="update-organization" class="required" />Organization
<br />
<li id="Family-Name" style="display: none;">
<input type="checkbox" class="Family-Name" value="Family-name" name="Family-name">
<label for="Family-Name"><em>*</em>Family Name:</label>
<input type="text" name="Family-Name" class="required">
</li>
<li id="Organization-Name" style="display: none;">
<inpname="Organization-name">
<label for="Organization-Name"><em>*</em>Organization Name:</label>
<input type="text" name="Organization-Name" class="required">
</li>
<div class="extraPersonTemplate">
<div class="controls-row">
<li id="Identification-Type" style="display: none;">Identification Type:
<select name="Identification-Type" class="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="1">--sdsd--</option>
<option value="2">--cxc--</option>
<option value="3">--cvcv--</option>
<select> <a id="Identification-Number" style="display: none;">
<input type="hidden" class="Identification-Number">
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number">
</a>
</li>
</div>
</div>
<div id="container"></div>
<a href="#" id="addRow" style="display: none;"><i class="icon-plus-sign icon-white">
</i> Add Identifier</a>
<li id="Adminsys-Type" style="display: none;">Admin System Type:
<select name="Adminsys-Type" class="Adminsys-Type">
<label for="Adminsys-Type">Admin Type:</label>
<option value="0">--Select--</option>
</select>
</li>
<li id="Adminsys-Number" style="display: none;">
<input type="checkbox" class="Adminsys-Number" value="Adminsys-Number" name="Adminsys-number">
<label for="Adminsys-Number"><em>*</em>Admin System Value:</label>
<input type="text" name=Adminsys-Number>
</li>
</ul>
<input type="submit" id="button" name="submit" value="Search">
</form>
JS:
$(document).ready(function () {
var counter = 0;
$('input[name=Organization-Name]').attr('disabled', true);
$('input[name=Identification-Number]').attr('disabled', true);
$('input[name=Family-Name]').attr('disabled', true);
$('input[name=Adminsys-Number]').attr('disabled', true);
$('#pancettaForm').change(function () {
$('.Organization-Name').click(function () {
if ($('.Organization-Name').is(':checked')) {
$('input[name=Organization-Name]').val('').attr('disabled', false);
} else {
$('input[name=Organization-Name]').attr('disabled', true);
}
});
$('select[name="Identification-Type' + counter + '"]').change(function () {
var $this = $('.Identification-Number');
var $input = $this.siblings('input[type=text]');
$input.attr("disabled", false);
$input.attr("disabled", ($(this).val() == '1111') ? true : false);
});
$('.Adminsys-Number').click(function () {
if ($('.Adminsys-Number').is(':checked')) {
$('input[name=Adminsys-Number]').val('').attr('disabled', false);
} else {
$('input[name=Adminsys-Number]').attr('disabled', true);
}
});
$('.Family-Name').click(function () {
if ($('.Family-Name').is(':checked')) {
$('input[name=Family-Name]').val('').attr('disabled', false);
} else {
$('input[name=Family-Name]').attr('disabled', true);
}
});
$('#Family-Name,#Identification-Number,#Organization-Name').hide();
if ($('#person').prop('checked')) {
$('#Family-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
} else if ($('#organization').prop('checked')) {
$('#Organization-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
}
});
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
$('<div/>', {
'class': 'extraPerson' + counter,
'id': 'extraPerson' + counter,
html: GetHtml() + '</i> Remove Identifier'
}).hide().appendTo('#container').slideDown('slow');
counter++;
});
$("#container").on('click', '.removeRow', function () {
//$("#extraPerson"+counter).remove();
if (counter < 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$(this).parent().remove();
});
function GetHtml() {
// var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
if (counter == 0) {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
counter++;
return $html.html();
} else {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
// $html.find('[id=Identification-Type]')[0].id="Identification-Type" + counter;
// var remove='</i> Remove Identifier';
return $html.html();
}
}
})
JSFIDDLE LINK
How can I dynamically change the name of select attribute so that I can selectively enable and disable input fields in multiple rows.
Hope this will help you a bit and I hope I got it correct:
I reworked you change function which determines the select boxes and enables the input field, like this
$('.Identification-Type').change(function () {
//#Identification-Type input
/** this can be used to count the input fields and use it in a loop later **/
var $inputFields = $('.extraPersonTemplate #Identification-Type input').length;
var $idNumber = $('input[name=Identification-Number]');
var $idNumber0 = $('input[name=Identification-Number0]');
($('select[name=Identification-Type]').val() == '1111') ? $idNumber.attr('disabled', true) : $idNumber.removeAttr('disabled');
($('select[name=Identification-Type0]').val() == '1111') ? $idNumber0.attr('disabled', true) : $idNumber0.removeAttr('disabled')
})
But from my point of view, this is not a the best approach since its not very dynamically.
If you manage to count up the select[name=Identification-Type] + counter not only for one input but for both of them like <input type="text" name="Identification-Number0"> and <input type="text" name="Identification-Number1"> it would be possible to include a loop within in this change function and loop over the $inputFields which are found
http://jsfiddle.net/xKL44/2/ this has helped me in the past... Try it out!
$('#wow').change(function() {
// Remove any previously set values
$('#show_box, #total_box').empty();
var sum = 0,
price;
$(this).find('option:selected').each(function() {
// Check that the attribute exist, so that any unset values won't bother
if ($(this).attr('data-price')) {
price = $(this).data('price');
sum += price;
$('#show_box').append('<h6>' + price + '</h6>');
}
});
$('#total_box').text(sum);
});

Adding checkboxes to textarea in JavaScript

I posted this earlier, but deleted the post due to formatting errors. I have a seen a few similar responses but they have been given negative scores so I thought I would post one up.
I have checkboxes that pull names from an SQL list using Ajax (which are echoed as checkboxes) and I want to when they are checked be posted in the textarea below when 'Add Selected Names' is clicked on
Here is my code, it functions for all and selects the figures ok (as the alerts test them). But doesn't pass the values to the textarea.
Jsfiddle:
http://jsfiddle.net/B4PvJ/1/
HTML:
<form name="promoForm4" method=post enctype=multipart/form-data action=cp007.php onSubmit="return validateForm();">
<ul class=mainForm id="mainForm_1">
<select name="nameoflist" onchange="changeFunc(this);">
<option value="" disabled="disabled" selected="selected">Select Recipients</option>
<option value="All Recipients">All Recipients</option>
<option value="Tech_List">Tech List</option>
</select>
<p>
<input type="checkbox" class="checkall">Check All
<br>
<br>
<div id="list_output" style="width:500px;height:500px;overflow:auto;"></div>
<p>Add Selected Names
<p>
<textarea readonly rows="10" cols="100" name="name_list_box"></textarea>
<p class="mainForm">
<input id="saveForm" class="mainForm" type="submit" value="Enter Track Details" />
</li>
</form>
JavaScript:
$(function () {
$(".add_names").click(function () {
alert("clicked");
var allVals = [];
$(".cb:checked").each(function () {
allVals.push($(this).val());
});
alert(allVals);
});
});
function changeFunc(obj) {
$('.checkall').prop('checked', false);
$("#list_output").empty();
var selectedValue = obj.options[obj.selectedIndex].value;
var url = "getnames.php?list_name=" + selectedValue;
$.get(url, function (data, status) {
var recep_list = data.split("^");
var r_len = recep_list.length;
for (var i = 0; i < r_len; i++) {
recep = recep_list[i].split("~");
$('#list_output').append('<input type="checkbox" class="cb" value="' + recep[1] + '" /> ' + recep[0] + '<br>');
}
});
}
$(".add_names").click(function () {
alert("clicked");
var allVals = [];
$(".cb").each(function () {
allVals.push($(this).val());
alert("somethingchecked");
});
var stringvals = allVals.join(" ");
$("#name_list_box").val($("#name_list_box").val() + stringvals);
alert(allVals);
});
$(".checkall").click(function () {
$('#list_output .cb').prop('checked', this.checked);
});
Many thanks
CP

Categories

Resources