Add selected options value into an array in javascript - javascript

I have 2 multiple select boxes where I select some of the options and add it to the other select box. When i click on save, the selected option values should be stored into one array and passed to the home controller. when i put alert i get the proper data but I get the below error in firebug console which i'm not able to solve it.Plse help me in this regard. here is the error and code.
for (var i = 0; i <= PairedSelectBox.options.length; i++) {
selectedClientChips.push(PairedSelectBox.options[i].value);
alert("selectedClientChips == " + selectedClientChips);
}
I get the error in console like this
TypeError: PairedSelectBox.options[i] is undefined
selectedClientChips.push(PairedSelectBox.options[i].value);
This is the html code:
<table>
<tr>
<td>
<label style="font-size: medium;">Client Chip details</label>
</td>
</tr>
<tr>
<td>
<label>Search</label>
<input type="text" id="searchId">
<input type="button" value="Go" onclick="getClientChipDetails();"></td>
</tr>
<tr>
<td>
<label style="font-size: small;">Client-Chip data</label>
</td>
<td></td>
<td>
<label style="font-size: small">Selected Client-Chip data</label>
</td>
</tr>
<tr>
<td>
<select id="MasterSelectBox" name="MasterSelectBox" size="10" multiple="multiple"></select>
</td>
<td>
<button id="btnAdd">> </button>
<br>
<button id="btnRemove">< </button>
</td>
<td>
<select id="PairedSelectBox" name="PairedSelectBox" size="10" multiple="multiple">
</select>
</td>
</tr>
</table>
This is the script:
$(document).ready(function () {
$('#MasterSelectBox').pairMaster();
$('#btnAdd').click(function () {
$('#MasterSelectBox').addSelected('#PairedSelectBox');
});
$('#btnRemove').click(function () {
$('#PairedSelectBox').removeSelected('#MasterSelectBox');
});
});

Try this. I modify your code.
HTML
<table>
<tr><td>Master select box</td><td>Paired select box</td></tr>
<tr>
<td>
<select id="MasterSelectBox" name="MasterSelectBox" size="10" multiple="multiple">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</td>
<td>
<button id="btnAdd"> > </button><br>
<button id="btnRemove"> < </button>
</td>
<td>
<select id="PairedSelectBox" name="PairedSelectBox" size="10" multiple="multiple"></select>
</td>
</tr>
</table>
<button id="save">Save</button>
<p id="output"></p>
Javascript
$(document).ready( function(){
$('#MasterSelectBox').pairMaster();
$('#btnAdd').click(function(){
$('#MasterSelectBox').addSelected('#PairedSelectBox');
});
$('#btnRemove').click(function(){
$('#PairedSelectBox').removeSelected('#MasterSelectBox');
});
$( "#save" ).click( function( e ) {
$( "#output" ).empty();
$.each( $( "#PairedSelectBox" ).val(), function( i, v ) {
$( "#output" ).append( $( "<span> " + v + " </span>" ) );
} );
} );
});
P.S. and use rawgit.com links to libraries, not raw.githubusercontent.com to attach scripts to jsfiddle.

#madhu i had update your code on jsfiddle with following code...
$(document).ready( function(){
var data=[];
//$('#MasterSelectBox').pairMaster();
$('#btnAdd').click(function(){
$("#MasterSelectBox option:selected").each(function () {
var selText = $(this).val();
data.push(selText);
});
$.each(data, function(val, text) {
$('#PairedSelectBox').append( $('<option>').text(text).attr('value',text));
});
});
$('#save_btn').click(function(){
alert("your data is"+JSON.stringify(data));
});
});
check your jsfiddle link

I got it... I had nott delcard the pairedSelectBox.
var PairedSelectBox = document.getElementById("PairedSelectBox");
// alert("PairedSelectBox==="+ PairedSelectBox);
for (var i = 0; i<PairedSelectBox.options.length; i++) {
selectedClientChips.push(PairedSelectBox.options[i].value);
//alert("selectedClientChips == " + selectedClientChips);
}
alert("selectedClientChips==="+selectedClientChips);

Related

JQuery hide all elements

I want to hide the table row if one of the <span> tags has the class from the value variable.
The variable val comes from a select box.
$(".hostgroup").change(function(event) {
var val = $(this).val();
console.log(val);
$("#groups > span").each(function() {
$(this).closest("tr").show();
$(this).removeClass("hd");
});
$("#groups > span").each(function() {
if ($(this).hasClass(val)) {} else {
$(this).closest("tr").hide();
$(this).closest("tr").addClass("hd");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="hostgroup" data-placeholder="Choose a hostgroup...">
<option value="delete">delete</option>
<option value="add">add</option>
<option value="OS">OS</option>>
</select>
<tr>
<td id="groups">
<span class="add">add,</span>
<span class="OS">OS,</span>
</td>
</tr>
<tr>
<td id="groups">
<span class="delete">delete,</span>
<span class="OS">OS,</span>
</td>
</tr>
For example: I select delete and it should only display table rows that not have got a <span> with the delete class. But now it will hide all results.
$("span.delete").parent().parent().hide()
will hide entire rows with spans in them with "delete" class. Swap the class to the value of your choosing in the "change" event.
Edit:
It should be like this:
$(".hostgroup").change(function(event) {
var val = $(this).val();
console.log(val);
$("span."+val).parent().parent().hide()
});
You could search for the class based on the tr, see the working example below :
$(".hostgroup").change(function(event) {
var val = $(this).val();
$("tr").each(function() {
if ( $(this).find('.' + val).length ) {
$(this).closest("tr").addClass("hd");
} else {
$(this).closest("tr").removeClass("hd");
}
});
});
.hd {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="hostgroup">
<option></option>
<option>add</option>
<option>OS</option>
<option>delete</option>
</select>
<table>
<tr>
<td class="groups">
<span class="add">add,</span>
<span class="OS">OS,</span>
</td>
</tr>
<tr>
<td class="groups">
<span class="delete">delete,</span>
<span class="OS">OS,</span>
</td>
</tr>
</table>

Enable/disable dropdowns when checkbox checked/unchecked

I'm creating a web app using Java servlets and JSP. I have a table which contains songs. Every song has its own checkbox and drop-down. like this:
You can see that taken songs have their checkbox and drop-down disabled and that's how I want it.
What I want is when the page loads all the drop-downs will be disabled, and when I check one of the available checkboxes the drop-down that is in the same line will be enabled and when I uncheck that checkbox the dropdown will be disabled again.
Here is the JSP code:
<table id="myTable">
<tr>
<th>Songs</th>
<th>Selected</th>
<th>#</th>
<th>Available/Taken</th>
</tr>
<c:forEach items="${Entities}" varStatus="loop">
<tr>
<td><c:out value="${Entities[loop.index]}"/></td>
<td><input id="checkbox1" type="checkbox" name="selected" value=" ${Entities[loop.index]}" ${checkboxDis[loop.index]} ><br></td>
<td>
<select name="myselect" id="drop" disabled >
<option selected disabled>#</option>
<option>Cmaj</option><option>Gmaj</option>
<option>Dmaj</option><option>Amaj</option>
<option>Emaj</option><option>Bmaj</option>
<option>Fmaj</option><option>Bb_maj</option>
<option>Eb_maj</option><option>Ab_maj</option>
<option>Db_maj</option><option>Gb_maj</option>
<option>Amin</option><option>Emin</option>
<option>Bmin</option><option>F#min</option>
<option>C#_min</option><option>G#_min</option>
<option>D#_min</option><option>Cb_maj</option>
<option>Gmaj</option><option>Dmaj</option>
<option>F#maj</option><option>Cmaj</option>
<option>Fmaj</option><option>Bb_maj</option>
<option>Eb_maj</option><option>Ab_maj</option>
<option>Db_maj</option><option>A#</option>
</select>
</td>
<td>
<c:choose>
<c:when test="${checkboxDis[loop.index].equals('disabled')}">
<i class="fa fa-ban" style="color:red;"></i>
</c:when>
<c:when test="${checkboxDis[loop.index].equals('')}">
<i class="fa fa-check-circle" style="color:green;"></i>
</c:when>
</c:choose>
</td>
</tr>
</c:forEach>
</table>
The jQuery code I've done so far:
var selected1 = new Array();
$(document).ready(function() {
$("input[type='checkbox']").on('change', function() {
if ($(this).is(":checked")) {
selected1.push($(this).val());
for (var i = 0; i < selected1.length; i++) {
if (selected1[i] == $(this).val()) {
$('#drop')[i].prop("disabled", false);
}
}
} else {
for (var i = 0; i < selected1.length; i++) {
if (selected1[i] == $(this).val()) {
selected1.splice(i, 1);
$('#drop')[i].prop("disabled", true);
}
}
}
});
});
The code isn't working because I don't know how to handle the drop-downs since they have the same names and ids.
Your IDs need to be unique - in this case not needed at all for enabling the select
$(function() {
$("input[type='checkbox']").on('change', function() {
$(this).closest("tr").find("select[name=myselect]").prop("disabled", !this.checked)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input id="checkbox_1" type="checkbox" name="selected" value="1"></td>
<td>
<select name="myselect" id="drop_1" disabled>
<option selected disabled>#</option>
<option>Cmaj</option>
<option>Gmaj</option>
<option>Dmaj</option>
<option>Amaj</option>
<option>Emaj</option>
<option>Bmaj</option>
<option>Fmaj</option>
<option>Bb_maj</option>
<option>Eb_maj</option>
<option>Ab_maj</option>
<option>Db_maj</option>
<option>Gb_maj</option>
<option>Amin</option>
<option>Emin</option>
<option>Bmin</option>
<option>F#min</option>
<option>C#_min</option>
<option>G#_min</option>
<option>D#_min</option>
<option>Cb_maj</option>
<option>Gmaj</option>
<option>Dmaj</option>
<option>F#maj</option>
<option>Cmaj</option>
<option>Fmaj</option>
<option>Bb_maj</option>
<option>Eb_maj</option>
<option>Ab_maj</option>
<option>Db_maj</option>
<option>A#</option>
</select>
</td>
</tr>
<tr>
<td><input id="checkbox_2" type="checkbox" name="selected" value="2"></td>
<td>
<select name="myselect" id="drop_2" disabled>
<option selected disabled>#</option>
<option>Cmaj</option>
<option>Gmaj</option>
<option>Dmaj</option>
<option>Amaj</option>
<option>Emaj</option>
<option>Bmaj</option>
<option>Fmaj</option>
<option>Bb_maj</option>
<option>Eb_maj</option>
<option>Ab_maj</option>
<option>Db_maj</option>
<option>Gb_maj</option>
<option>Amin</option>
<option>Emin</option>
<option>Bmin</option>
<option>F#min</option>
<option>C#_min</option>
<option>G#_min</option>
<option>D#_min</option>
<option>Cb_maj</option>
<option>Gmaj</option>
<option>Dmaj</option>
<option>F#maj</option>
<option>Cmaj</option>
<option>Fmaj</option>
<option>Bb_maj</option>
<option>Eb_maj</option>
<option>Ab_maj</option>
<option>Db_maj</option>
<option>A#</option>
</select>
</td>
</tr>
</table>
Change your JSP to this:
<td><input id="checkbox_${checkboxDis[loop.index]}" type="checkbox" name="selected" value="${Entities[loop.index]}"><br></td>
<td>
<select name="myselect" id="drop_${checkboxDis[loop.index]}" disabled >
<option selected disabled>#</option>
<option>Cmaj</option><option>Gmaj</option>
<option>Dmaj</option><option>Amaj</option>
<option>Emaj</option><option>Bmaj</option>
<option>Fmaj</option><option>Bb_maj</option>
<option>Eb_maj</option><option>Ab_maj</option>
<option>Db_maj</option><option>Gb_maj</option>
<option>Amin</option><option>Emin</option>
<option>Bmin</option><option>F#min</option>
<option>C#_min</option><option>G#_min</option>
<option>D#_min</option><option>Cb_maj</option>
<option>Gmaj</option><option>Dmaj</option>
<option>F#maj</option><option>Cmaj</option>
<option>Fmaj</option><option>Bb_maj</option>
<option>Eb_maj</option><option>Ab_maj</option>
<option>Db_maj</option><option>A#</option>
</select>
</td>
Now your checkboxes and dropdowns have corresponding IDs which you can then use with jQuery:
var selected1 = new Array();
$(document).ready(function() {
$("input[type='checkbox']").on('change', function() {
if ($(this).is(":checked")) {
selected1.push($(this).val());
$('#drop_' + $(this).val()).prop("disabled", false);
} else {
$('#drop_' + $(this).val()).prop("disabled", true);
// Instead of a for-loop for removing the unchecked song,
// you can also use Array.filter():
selected1 = selected1.filter(song_id => song_id !== $(this).val());
/*
for (var i = 0; i < selected1.length; i++) {
if (selected1[i] == $(this).val()) {
selected1.splice(i, 1);
}
}
*/
}
});
});

unable to fetch results from search page while using ajax with checkbox

<form enctype="multipart/form-data">
<table>
<tr>
<td>
<font style="font-size:20px">Snp Id:</font>
</td>
<td><input type="text" name="isnp_id" id="isnp_id" placeholder="Ex:SCcLG07_1001342" size=20 style="font-size:18px"></td>
</tr>
<tr>
<td>
<font style="font-size:20px">Gene Id:</font>
</td>
<td><input type="text" name="igene" id="igene" placeholder="Ex:C.cajan_17400" size=20 style="font-size:18px"></td>
</tr>
<tr>
<td>
<font style="font-size:20px">Chromosome:</font>
</td>
<td><input type="text" name="ichr" id="ichr" placeholder="Ex:CcLG07" size=20 style="font-size:18px"></td>
<td> position from </td>
<td><input type="text" name="posstart" id="posstart" placeholder="Ex: 1" size="20"> to <input type="text" name="posend" id="posend" placeholder="Ex:100" size="20">
</td>
</tr>
<tr>
<td>
<font style="font-size:20px">Genotype name:</font>
</td>
<td> <select style="font-size:18px" id="sg" name="sg">
<option value="">Select</option>
<option value="icpl_131">icpl_131</option>
<option value="icpa_2039">icpa_2039 </option>
<option value="icpl_96061">icpl_96061 </option>
</select> </td>
<td> between </td>
<td> <select style="font-size:18px" id="sg2" name="sg2">
<option >Select</option>
<option value="icpa_2039">icpa_2039 </option>
<option value="icpl_131">icpl_131</option>
<option value="icpl_96061">icpl_96061 </option>
</select>
</td>
</tr>
<tr>
<td><input type="checkbox" name="cbc" id="cbc" value="cb_class" /> </td>
<td>
<font style="font-size:20px">Classification:</font>
</td>
<td><select style="font-size:18px" name="sclass" id="sclass">
<option value="all" selected="selected">Select</option>
<option value="intergenic">Intergenic</option>
<option value="intronic">Intronic</option>
<option value="non_synonymous_coding">Non Synonymous Coding</option>
<option value="synonymous_coding">Synonymous Coding</option>
</select> </td>
</tr>
<tr>
<td><input type="checkbox" name="cbv" id="cbv" value="cb_vtype" /></td>
<td>
<font style="font-size:20px">Varation Type:</font>
</td>
<td><select style="font-size:18px" name="svtype" id="svtype">
<option value="all" selected="selected">Select</option>
<option value="snp">Snp</option>
<option value="insertion">Insertion</option>
<option value="deletion">Deletion</option>
</select> </td>
</tr>
<tr>
<td><input type="checkbox" name="cbf" id="cbf" value="cb_fc" /></td>
<td>
<font style="font-size:20px">Functional Class:</font>
</td>
<td><select style="font-size:18px" name="sfclass" id="sfclass">
<option value="all" selected="selected">Select</option>
<option value="missense">Missense</option>
<option value="nonsense">Nonsense</option>
<option value="silent">silent</option>
</select>
</td>
</tr>
<tr>
<td><input type="reset" name="reset" value="Reset" style="font-size:18px">
<input type="button" name="submit" id="goto" value="Search" onclick="loadData('1')" style="font-size:18px"><span id="loadings"></span></td>
</tr>
</table>
</form>
Now jquery ajax function code:
<script type="text/javascript">
function loading_show() {
$('#loadings').html("<img src='js/loader2.gif'/>").fadeIn('fast');
}
function loading_hide() {
$('#loadings').fadeOut('fast');
}
function loadData(page) {
$('#tbl').hide();
loading_show();
$.ajax({
type: "POST",
url: "newrs_old1.php",
data: "page=" + page + "&isnp_id=" + $('#isnp_id').val() + "&igene=" + $('#igene').val() + "&ichr=" + $('#ichr').val() + "&posstart=" + $('#posstart').val() + "&posend=" + $('#posend').val() + "&sg=" + $('#sg').val() + "&sg2=" + $('#sg2').val() + "&cbc=" + $('#cbc').val() + "&sclass=" + $('#sclass').val() + "&cbv=" + $('#cbv').val() + "&svtype=" + $('#svtype').val() + "&cbf=" + $('#cbf').val() + "&sfclass=" + $('#sfclass').val(),
success: function(msg) {
$("#container1").ajaxComplete(function(event, request, settings) {
loading_hide();
$("#container1").html(msg);
});
}
});
}
$(document).ready(function() {
$(document).bind('keypress', function(e) {
if (e.keyCode == 13) {
$('#goto').trigger('click');
}
});
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], textarea").val("");
});
//loadData(1); // For first time page load default results
$('#container1 .pagination li.active').live('click', function() {
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click', function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if (page != 0 && page <= no_of_pages) {
loadData(page);
} else {
alert('Enter a PAGE between 1 and ' + no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
</script>
Without using jQuery and AJAX, search page is working well, when i started to use jquery and ajax to make it paginate ,checkbox creating issue here.
After implementation of ajax, input given in the search page is not taking by the script ,it is only taking checkbox values if checked.
I can get only checkbox based search results only ,remaining search columns are not working.
If i removed checkbox from ajax i can get remaining search column results. but i want both working because i am using combination search.
Plz help me to solve this issue. i dont know how to implement this issue in jquery ajax
try using formdata to pass ajax something like
function SubmitForm() {
var data = $("#yourform").serialize();
var url = "Your URL"
var form = $('#yourform')[0]
var formdata = false;
if (window.FormData) {
formdata = new FormData(form);
}
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formdata ? formdata : data,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
//whatever
}
just add unique id in you form tag like below
<form enctype="multipart/form-data" id="form1" >
and get that form data using form id and pass in ajax like below
data: $('#form1').serialize();
serialize will pass all form field data in ajax.
you can get that data using $_POST

make an input text into read only when one value is selected from drop down list using jquery

i have one select box there in that options are,
none
current
future
if you select 'NONE' the all text box should be editable.
if you select 'current' the class="current" those text box should be editable and remaining should be only readonly.
similarly same like to future also. When i select future the future text boxes should be editable and remaining should be readonly
$('#cognizant').change(function(){
if(this.value == ""){
$('.current').prop('readonly',true);
} else{
$('.current').prop('readonly',false);
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="curator">
<tbody id="tableToModify">
<tr>
<td>
<select id="cognizant" class="discount-type" >
<option value="">none</option>
<option value="1">current</option>
<option value="2">future</option>
</select>
</td>
<td>
<input type="text" id="clientbi" class="current"/>
<input type="text" id="cognizantbi" class="current"/>
<input type="text" id="futurevsm" class="future" />
<input type="text" id="futuresymbols" class="future" />
</td>
</tr>
</tbody>
</table>
Let's change your javascript code only.
We need to use jQuery's change() function (documentation) and then validate the selected option.
The final code:
$('#cognizant').change(function(){
var value = $(this).val();
if(value == ''){
// NONE
$('#curator input[type="text"]').removeAttr('readonly');
}
else if(value == '1'){
// CURRENT
$('#curator input[type="text"]').attr('readonly', true);
$('#curator .current').removeAttr('readonly');
}
else if(value == '2'){
// FUTURE
$('#curator input[type="text"]').attr('readonly', true);
$('#curator .future').removeAttr('readonly');
}
});
See it in action: https://jsfiddle.net/x5fdLqff/4/
$('#cognizant').change(function(){
switch(this.value) {
case "":
$('.current').prop('readonly',false);
$('.future').prop('readonly',false);
break;
case "1":
$('.current').prop('readonly',false);
$('.future').prop('readonly',true);
break;
case "2":
$('.current').prop('readonly',true);
$('.future').prop('readonly',false);
break;
}
}).change();
<table id="curator">
<tbody id="tableToModify">
<tr>
<td>
<select id="cognizant" class="discount-type" >
<option value="">none</option>
<option value="current">current</option>
<option value="future">future</option>
</select>
</td>
<td>
<input type="text" id="clientbi" class="current myinputs"/>
<input type="text" id="cognizantbi" class="current myinputs"/>
<input type="text" id="futurevsm" class="future myinputs" />
<input type="text" id="futuresymbols" class="future myinputs" />
</td>
</tr>
</tbody>
</table>
<script>
$('#cognizant').change(function(){
var type = $("#cognizant").val();
$( ".myinputs" ).each(function( index ) {
$( this ).prop('readonly', false);
});
if(type != ""){
$("."+type).each(function( index ) {
$( this ).prop('readonly', true);
});
}
});
</script>
I have change option value in select box and made little change in javascript code.
hope it works for you.
As an alternative approach, with a small change in the html. You add a class name of 'none' to all the input fields, which is the same as option 1.
<table id="curator">
<tbody id="tableToModify">
<tr>
<td>
<select id="cognizant" class="discount-type" >
<option value="">none</option>
<option value="1">current</option>
<option value="2">future</option>
</select>
</td>
<td>
<input type="text" id="clientbi" class="current none"/>
<input type="text" id="cognizantbi" class="current none"/>
<input type="text" id="futurevsm" class="future none" />
<input type="text" id="futuresymbols" class="future none" />
</td>
</tr>
</tbody>
</table>
Then the jQuery to be like this. Comments explain approach.
$(function(){
$('#cognizant').on("change", function() {
//Set all text boxes to readonly
$("input[type='text']").prop("readonly", true);
//Select the option text, based on its value.
var text = $("#cognizant option[value='"+$(this).val()+"']").text();
//Set the property readonly to false on the selected class.
$("."+text).prop('readonly', false);
}).trigger("change");
});

Adding new row to the table using javascript / jquery

I want to add row to the table on clicking Add button and delete row using Delete button using javascript/jquery. I have tried writing the following code:
<script src="/js/jquery-2.0.3.js"></script>
<script>
/* Javascript for phone numbers*/
$(document).ready(function()
{
var counter = 2;
var count= 4;
$("#add_phone").click(function()
{
alert("whoah it worked");
if(counter>=count)
{
alert("Only " + count + " Phone number allowed.");
return false;
}
var htmlToAppend = '<tr id="pn'+ counter +'"><th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
newTableRow.appendTo("#phone_number");
counter++;
});
$("#delete_phone").click(function()
{
if(counter==2)
{
alert("Cannot remove phone number");
return false;
}
counter--;
$("#pn" + counter-1).remove();
});
});
But the alert message alert("whoah it worked"); doesn't get displayed i.e its not entering the function.
<div class="info_type">
Phone numbers <hr>
<table id="phone_number">
<tr id="pn1">
<th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td>
</tr>
</table>
<input type="button" id="add_phone" value="Add"/>
<input type="button" id="delete_phone" value="Delete"/>
</div>
I really want this solution. Can anybody help me??
PS: I am using Ruby on rails
Your string append is not well formed.
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"> <option value="home">home</option> <option value="Business">Business</option> <option value="Business2">Business 2</option></select> </th><td><input type="text"/></td></tr>';
Working sample in fiddle http://jsfiddle.net/shree/jNA4x/
try to rewrite htmlToAppend variable with a \n\ in the end of each line
demo
You can't have line breaks in your htmlToAppend variable,
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"><option value="home">home</option><option value="Business">Business</option><option value="Business2">Business 2</option></select></th><td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
Example Code
A common pitfall for me as well.
increment the counter you did not increments it.
for more help use like the below example.
<html>
<h1>Add remove dynamically</h1>
<head>
<title></title>
</head>
<body>
Living in:
<table id="purchaseItems" name="purchaseItems" style="display: inline-table;">
<tr id="tr_1">
<td>
<input type="text" name="living_1" class="tbDescription next" required />
</td>
<td>
<input type="text" name="biggest_1" class="next" required />
</td>
<td>
<input type="text" name="nextbiggest_1" class="nextRow" required />
</td>
<td>
<input type="button" name="addRow[]" id="remove_1" class="removeRow" value='-' />
</td>
<td>
<input type="button" name="addRow[]" id="add_1" class="add" value='+' />
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$("#remove_1").hide();
$(document).ready(function () {
$(document).on('click', '#purchaseItems .add', function () {
var total_row = $('#purchaseItems tr').length;
var rows = $('#purchaseItems tr').length+1;
if(total_row < 5)
{
// clear the values
$('#purchaseItems tr:last').after('<tr id="tr_'+rows+'"><td><input type="text" name="living_'+rows+'" id="living_'+rows+'" class="tbDescription next"></td><td><input type="text" name="biggest_'+rows+'" id="biggest_'+rows+'" class="next"></td><td><input type="text" name="nextbiggest_'+rows+'" id="nextbiggest_'+rows+'" class="nextRow"></td><td><input type="button" name="addRow[]" id="remove_'+rows+'" class="removeRow" value="-"></td><td><input type="button" name="addRow[]" id="add_'+rows+'" class="add" value="+"></td></tr>');
$(".add").hide();
$(".removeRow").show();
$("#add_"+rows).show();
}
else
{
alert("Maximum limit reached.")
}
});
$(document).on('keypress', '#purchaseItems .next', function (e) {
if (e.which == 13) {
var v = $(this).index('input:text');
var n = v + 1;
$('input:text').eq(n).focus();
//$(this).next().focus();
}
});
$(document).on('keypress', '#purchaseItems .nextRow', function (e) {
if (e.which == 13) {
$(this).closest('tr').find('.add').trigger('click');
$(this).closest('tr').next().find('input:first').focus();
}
});
$(document).on('click', '#purchaseItems .removeRow', function () {
var total_row = $('#purchaseItems tr').length;
if ($('#purchaseItems .add').length > 1) {
$(this).closest('tr').remove();
var last_tr_id = $('#purchaseItems tr:last').attr("id").split("_")[1];
$("#add_"+last_tr_id).show();
}
if ($('#purchaseItems .add').length == 1) {
$(".removeRow").hide();
}
});
});
</script>
Try this way using Jquery
<form id="myForm">
<div class="clonedInput">
<input type="text" class="phone_oa" id="textPhone1" name="input1" placeholder="Enter phone number" style="width: 110px;" />
<input type="button" name="btnDelete1" class="btnDel" value="Remove" disabled="disabled" />
</div>
<div id="addDelButtons" style="margin-top: 10px;">
<button type="button" id="btnAdd" class="btn" >Add Another Number</button>
</div>
</form>
Script
var inputs = 1;
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name','input'+ (++inputs) ).val('');
c.children(':text').attr('id','textPhone'+ (inputs) ).val('');
c.children(':button').attr('name','btnDelete'+ (inputs) );
$('.clonedInput:last').after(c);
$('#btnAdd').attr('disabled',($('.clonedInput').length > 4));
});
$('.btnDel').click(function() {
if (confirm('Confirm delete?')) {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel').attr('disabled',($('.clonedInput').length < 2));
$('#btnAdd:disabled').removeAttr('disabled');
fixNames();
}
});
function fixNames(){
var i = inputs;
while(i--) {
$('input:text')[i].name = 'input'+ (i+1);
$('input:button')[i].name = 'btnDelete'+ (i+1);
}
}
DEMO

Categories

Resources