How to find dynamically created element using jQuery selectors? - javascript

I have a form which has certain elements in it. I want to get all the elements inside the form regardless of their depth.
This is my test code
$(document).ready(function(){
//script.init(markchaining);
$('#checkbutton').click(function(){
$('#saveForm :input').each(function(key){
if($(this).is('select'))
{
var id = $(this).attr('id');
console.log('id is '+id);
$(this).trigger('change');
console.log('if-> Element name is '+$(this).attr('name'));
}
else
{
console.log('else-> Element name is '+$(this).attr('name'));
}
});
});
});
function addRow(ele,name)
{
var id = ele.id;
$('#'+id+'').closest('tr').after('<tr><td class="label-cell">New Row</td><td><input type="text" name="'+name+'" /></td></tr>');
}
My Problem
I also have dynamic elements which will be created on certain select change events during the iteration. I want to get these dynamically created elements as I iterate through my form.
I am not able to access the "New Row" element which gets created dynamically on clicking the 'check' button
This is my complete test code

Just added a count variable to distinguish the names on console. https://jsfiddle.net/ztpjacyu/
$(document).ready(function() {
//script.init(markchaining);
$('#checkbutton').click(function() {
$('#saveForm :input').each(function(key) {
if ($(this).is('select')) {
var id = $(this).attr('id');
console.log('id is ' + id);
$(this).trigger('change');
console.log('if-> Element name is ' + $(this).attr('name'));
} else {
console.log('else-> Element name is ' + $(this).attr('name'));
}
});
});
//Clicked twice to show you the console
$('#checkbutton').click();
$('#checkbutton').click();
});
var count = 0;
function addRow(ele, name) {
var id = ele.id;
$('#' + id + '').closest('tr').after('<tr><td class="label-cell">New Row</td><td><input type="text" name="' + name + ++count + '" /></td></tr>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="mainform" id="saveForm" action="#">
<!--##GENERAL##-->
<input type="button" name="checkbutton" id="checkbutton" value="Check" /> <- Moved here so that you can see the console
<div id="fromuser">
<table width="100%" id="userTable">
<tr id="ReportNameRow">
<td class="label-cell">Report Name :</td>
<td>
<input type="text" name="CustomReportName" id="CustomReportName" />
</td>
</tr>
<tr id="ReportNamrRow">
<td class="label-cell">* Saved Report Name :</td>
<td>
<select name="rname" id="rname" onChange="addRow(this,'MYID');">
<option value="">---Select---</option>
<option value="Cash_Position">Cash Position</option>
<option value="Detail_Report">Detail Report</option>
<option value="FCCS/FBPS_Detail_Report">FCCS/FBPS Detail Report</option>
<option value="Reconciliation_Report">Reconciliation Report</option>
<option value="Statement_Report">Statement Report</option>
<option value="CustomReport">Enter Custom Report Name</option>
</select>
</td>
</tr>
<input type="hidden" name="hiddenid" value="I am hidden" id="hiddenid" />
<tr id="submit">
<td class="label-cell"></td>
<td>
<input type="submit" name="submitbutton" id="submitbutton" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
Update
if you want the element to be there before you execute your each , you can do this : https://jsfiddle.net/jbrt3Led/
$('#checkbutton').click(function() {
$("#rname").trigger('change');
$('#saveForm :input').each(function(key) {
if ($(this).is('select')) {
var id = $(this).attr('id');
console.log('id is ' + id);
console.log('if-> Element name is ' + $(this).attr('name'));
} else {
console.log('else-> Element name is ' + $(this).attr('name'));
}
});
});

Related

Trigger change issue in jQuery

I have a table where I have multiple rows, one of the columns being an input for the charge. The html is below:
<tbody>
#foreach($shipment_details as $sd)
<tr style="height:40px" tr id="row{{$sd->id}}">
<td style="width:8%;text-align:center;">
<input type="text" id="piecesNumber" class="form-control" placeholder="No. Pieces" required name="shipment_details[{{$sd->id}}][piecesNumber]" value="{{$sd->pieces_number}}">
</td>
<td style="width:16%;text-align:center;">
<select id="pieces_type" class="form-control full-width" required name="shipment_details[{{$sd->id}}][piecesType]">
#foreach($cPiecetypes as $cPt)
<option value="{{$cPt->id}}"
#if ($sd->pieces_type == $cPt->id) selected="selected"
#endif>{{$cPt->label}}</option>
#endforeach
</select>
</td>
<td>
<select id="pieces_type" class="form-control full-width" required name="shipment_details[{{$sd->id}}][rateType]">
#foreach($cRatetypes as $cRt)
<option value="{{$cRt->id}}"
#if ($sd->rate_type == $cRt->id) selected="selected"
#endif>{{$cRt->label}}</option>
#endforeach
</select>
</td>
<td style="width:16.5%;text-align:center;">
<input type="text" id="weight" class="form-control" placeholder="Weight" required name="shipment_details[{{$sd->id}}][weight]" value="{{$sd->weight}}">
</td>
<td style="width:16.5%;text-align:center;">
<select id="hazmat" class="form-control full-width" required name="shipment_details[{{$sd->id}}][hazmat]">
<option value="0"
#if ($sd->hazmat = 0) selected="selected"
#endif>No</option>
<option value="1"
#if ($sd->hazmat = 1) selected="selected"
#endif>Yes</option>
</select>
</td>
<td style="width:16.5%;text-align:center;">
<input type="text" id="description" class="form-control" placeholder="Description" required name="shipment_details[{{$sd->id}}][description]" value="{{$sd->description}}">
</td>
<td style="width:16.5%;text-align:center;">
<input type="text" id="charge" class="form-control charges" placeholder="Charge" required name="shipment_details[{{$sd->id}}][charge]" value="{{$sd->charge}}">
</td>
<td><button type="button" name="removeExisting" id="{{$sd->id}}" class="btn btn-danger btn_removeExisting">X</button></td>
</tr>
#endforeach
</tbody>
As you see, there is a button at the end of reach row with the class of "btn_removeExisting" which connects to this script:
$(document).on('click', '.btn_removeExisting', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
$( '.charges' ).trigger( 'change' );
alert('removeExisting');
});
The alert is only there to notify me that the script has completed correctly, which is where my problem is. By pressing the button, it correctly deletes the correct row, and alerts me, but the trigger in the middle is where my problem originates.
The script regarding my change of charge trigger:
$(document).on('change', '.charges', function() {
var sum = 0.00;
$('.charges').each(function(){
sum += +$(this).val();
});
$('input[name^="freightBillSubtotal"]').val(sum.toFixed(2));
calcTotal();
});
Now what's odd is if I just change a charge input, the code works, so if I change the charge on one line from 10.00 to 0.00, the subtotal subtracts 10.00. But for some reason it won't do the same for when an entire row (and it's specific charge) is deleted.
Instead of trying to trigger events manually like that, it is better to make a function and call it from both events:
$(document).on('click', '.btn_removeExisting', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
calcSum();
alert('removeExisting');
});
$(document).on('change', '.charges', calcSum);
function calcSum() {
var sum = 0.00;
$('.charges').each(function() {
sum += $(this).val();
});
$('input[name^="freightBillSubtotal"]').val(sum.toFixed(2));
calcTotal();
});
Note: I assumed there was a harmless typo on your line:
sum += +$(this).val();
so I changed it to:
sum += $(this).val();

Table Add More Row using javascript

I am adding dynamic row to table. But when adding new row, I want to replace some string on new row. But it is not working.
<table id="testTable">
<tr id="row_1">
<td>
<select onchange="changeCustomCategory(this.value,'1');" id="_cid" name="_cid[0]" >
<option value="">--Select Product--</option>
<option value="test">Test</option>
</select>
<input type="text" onchange="_doVariation(1);" value="1" id="_qty" name="_qty[0]"/>
<input type="text" class="textfield" value="0.00" id="item1_total" name="item1_total" readonly>
</td>
</tr>
</table>
<input type="hidden" value="1" id="total_row">
<input type="button" onclick="addRow()" value="Add Row">
This is my HTML code.
function addRow(){
var total_row = document.getElementById("total_row").value;
var _previousId = parseInt(total_row);
var new_id = parseInt(total_row) + 1;
document.getElementById("total_row").value = new_id;
var table = document.getElementById("testTable");
jQuery("#"+ table.rows[0].id).clone().appendTo("#testTable");
var totalTableRow = table.rows.length;
var currentRow = table.rows[totalTableRow-1];
currentRow.id = "row_"+new_id;
currentRow.innerHTML = currentRow.innerHTML.replace('_cid\['+ new_id-1 +'\]','_cid['+new_id+']');
currentRow.innerHTML = currentRow.innerHTML.replace(new RegExp("changeCustomCategory(this.value,'"+_previousId+"')","g"),'changeCustomCategory(this.value,'+new_id+')');
currentRow.innerHTML = currentRow.innerHTML.replace('_doVariation('+_previousId+')','_doVariation('+new_id+')');
}
You can perform your changes as the following:
//....
var newRow = jQuery("#"+ table.rows[0].id).clone().appendTo("#testTable");
//Change1
newRow.attr('name', '_cid['+new_id+']');
//Change2:
newRow.find('select').removeAttr('onchange').change(function() {
changeCustomCategory(this.value, new_id);
});
//Change3:
newRow.find('input:first').removeAttr('onchange').change(function() {
_doVariation(new_id);
});
//....
Demo: https://jsfiddle.net/4c0v2d50/
I would suggest sticking to jquery functions and not mixing too much with plain javascript. It makes it easier to code and follow.
I believe this is what your trying to do:
change HTML
id="_cid" name="_cid[0]"//change in select to
class="_cid" name="_cid[]"//_cid[] will automatically increment
id="_qty" name="_qty[0]"//same in input
class="_qty" name="_qty[]"
//you should also change
id="item1_total"
class="item1_total"
Javascript
function addRow(){
var new_id = $("#total_row").val() + 1;
$("#total_row").val(new_id);
var $currentRow = $("#testTable tr:first").clone();
$("#testTable").append(currentRow);
$currentRow.attr(id,"row_"+new_id);
$currentRow.find('select').attr('onclick',"changeCustomCategory(this.value,'"+new_id+"')");
$currentRow.find('._qty').attr('onchange','_doVariation('+new_id+')');
}
Removed the inline binding and bound to the element in the logic. Started changing the first thing you were trying to do with a regex. You can see how you like this approach.
jQuery(function($) {
//cache selectors
var $total_row = $("#total_row"),
$table = $("#testTable");
$(".addRow").on('click', function addRow() {
var total_row = $total_row.val(),
_previousId = parseInt(total_row),
new_id = _previousId + 1;
$total_row.val(new_id);
var $new_row = $table.find("tr").eq(0).clone();
$new_row.attr("id", "row_"+ new_id);
$new_row.find("select").attr("name", "_cid["+ (new_id - 1) +"]");
$table.append($new_row);
// currentRow.innerHTML = currentRow.innerHTML.replace('_cid\[' + new_id - 1 + '\]', '_cid[' + new_id + ']');
// currentRow.innerHTML = currentRow.innerHTML.replace(new RegExp("changeCustomCategory(this.value,'" + _previousId + "')", "g"), 'changeCustomCategory(this.value,' + new_id + ')');
// currentRow.innerHTML = currentRow.innerHTML.replace('_doVariation(' + _previousId + ')', '_doVariation(' + new_id + ')');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="testTable">
<tr id="row_1">
<td>
<select onchange="changeCustomCategory(this.value,'1');" id="_cid" name="_cid[0]">
<option value="">--Select Product--</option>
<option value="test">Test</option>
</select>
<input type="text" onchange="_doVariation(1);" value="1" id="_qty" name="_qty[0]" />
<input type="text" class="textfield" value="0.00" id="item1_total" name="item1_total" readonly>
</td>
</tr>
</table>
<input type="hidden" value="1" id="total_row">
<input type="button" value="Add Row" class="addRow">
function addRow(){
var total_row = parseInt(document.getElementById("total_row").value);
var _previousId = parseInt(total_row);
var new_id = parseInt(total_row) + 1;
var total_row = $("#total_row").val();
var _previousId = parseInt(total_row);
var new_id = parseInt(total_row) + 1;
$("#total_row").val(new_id);
var currentRow = $("#testTable tr:first").clone();
$("#testTable").append(currentRow);
$(currentRow).find('#_cid').attr("name","_cid["+new_id+"]");
$(currentRow).find('#_qty').attr("name","_qty["+new_id+"]");
$(currentRow).attr("id","row_"+new_id);
$(currentRow).find('#_cid').attr('onclick',"changeCustomCategory(this.value,'"+new_id+"')");
$(currentRow).find('#_qty').attr('onclick','_doVariation('+new_id+')');}
Working fiddle.
The id attribute should be unique so you could replace the duplicate ones by class attributen example :
<select class="_cid" name="_cid[0]" >
<input type="text" value="1" class="_qty" name="_qty[0]"/>
Better if you could avoid the inline-event onclick() and the overriding of parameters in every clone and define a general event one time and it will work for all the element, example :
$('body').on('change','._cid', function(){
//You code here
})
You don't need to increment the names you have just to leave the array signs empty [] and it will be incremented automatically, example :
<select class="_cid" name="_cid[]" >
<input type="text" value="1" class="_qty" name="_qty[]"/>
Hope this helps.
$(function(){
$('body').on('change','._cid', function(){
var id_number = $(this).parents('tr').attr('id').split('_')[1];
changeCustomCategory($(this).val(),id_number);
})
$('body').on('change','._qty', function(){
var id_number = $(this).parents('tr').attr('id').split('_')[1];
_doVariation(id_number);
})
})
function addRow()
{
var new_id = $('.row').length + 1;
var new_row = $("#testTable tr:first").clone().attr('id','row_'+new_id);
$("#testTable").append(new_row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testTable">
<tr id="row_1" class="row">
<td>
<select class="_cid" name="_cid[]" >
<option value="">--Select Product--</option>
<option value="test">Test</option>
</select>
<input type="text" value="1" class="_qty" name="_qty[]"/>
<input type="text" class="textfield" value="0.00" class="item1_total" name="item1_total" readonly>
</td>
</tr>
</table>
<input type="button" onclick="addRow()" value="Add Row">

Jquery forms with adaptive table from selector

I need your help. Trying to build form in php + jquery, and have trouble with some functionality.
For example, I have this code:
<form action="" method="post" id="multiform">
<!-- Product selector -->
<table class="multi" id="MultiRow">
<tr><td>
<select name="store[product][]" required>
<option value="" selected="selected">-Product-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
<option value="19041">TRAVEL</option>
<option value="19063">HOUSEHOLD</option>
</select>
</td>
<!-- /Product selector -->
</table>
<input type="submit" value="ok">
How can I do that, If selected value is 430 or 440, then at right side inserts
<td><input type="text" id="motor[]" name="multiarray[vehicle_type][]"></td>
<td><input type="text" id="deadline[]" name="multiarray[end_date][]"></td>
<td><a class="del" href="#">DELETE BUTTON</a></td>
If selected value is 19041 or 19063, then inserts
<td><input type="text" id="location[]" name="multiarray[travel_location][]"></td>
<td><a class="del" href="#">DELETE BUTTON</a></td>
I need that there also will be +Add button and -delete button where i write:
<a class="del" href="#">DELETE BUTTON</a>
But for datepicker functionality I need that id for inputs will be unique, for ex: id="location1" , at next added row id="location2".
JsFiddle
$("#productselect").change(function(){
var select = document.getElementById("productselect");
var selecedproduct = select.options[select.selectedIndex].value;
$("tr[id^='forselect']").remove();
if(selecedproduct==430 || selecedproduct==440 )
{
var html ='<tr id="forselect"><td><input type="text" id="motor[]" name="multiarray[vehicle_type][]"></td>';
html +='<td><input type="text" id="deadline[]" name="multiarray[end_date][]"></td>';
html +='<td><a class="del" OnClick="removetags();return false;" href="#">DELETE BUTTON</a></td></tr>';
html +='<tr id="forselect"><td>add datepicker </td></tr>';
$("#MultiRow").append(html);
}
else if(selecedproduct==19041 || selecedproduct==19063 )
{
var html ='<tr id="forselect"><td><input type="text" id="location[]" name="multiarray[travel_location][]"></td>';
html +=' <td><a class="del" OnClick="removetags();return false;" href="#">DELETE BUTTON</a></td></tr>';
html +='<tr id="forselect"><td>add datepicker </td></tr>';
$("#MultiRow").append(html);
}
});
deldatepicker = function deldatepicker(id)
{
$("#remove"+id).remove();
}
adddatepicker = function adddatepicker()
{
var N = $("input[id^='location']").length;N++;
var html ='<tr id="remove'+N+'"><td><input type="text"id="location'+N+'" placeholder="date"></td><td><button OnClick="deldatepicker('+N+')">delete datepicker </button> </td></tr>';
$("#MultiRow").append(html);
$("#location"+N).datepicker();
}
removetags = function removetags()
{
$("tr[id^='forselect']").remove();
}
It may help you for you work.
Here it is.
Since you need the ids to be unique I have used Date.now() and then object.now.getUTCMilliseconds(). That will ensure that event when you delete and reinsert another row with same rowIndex it will not crash. Then the rest is trivial!
jQuery(document).ready(function(){
jQuery('select').on('change', function(e){
var tr = jQuery(this).closest('tr').get(0);
var cell = tr.insertCell(1);
var now = Date.now();
switch(jQuery('option:selected', this).val()){
case '430':
case '440':
cell.innerHTML = "<td><input type='text' id='motor[]' name='multiarray[vehicle_type][]'></td><td><input type='text' id='deadline[]' name='multiarray[end_date][]'></td><td><a class='del' href='#'>DELETE BUTTON</a></td><td><a class='del' href='#'>DELETE BUTTON</a></td>";
break;
cell.innerHTMl = "<td><input type='text' id='location"+now.getUTCMilliseconds()+"[]' name='multiarray[travel_location][]'></td><td><a class='del' href='#'>DELETE BUTTON</a></td><td><a class='del' href='#'>DELETE BUTTON</a></td>";
case '19041':
case '19063':
break;
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form action="" method="post" id="multiform">
<!-- Product selector -->
<table class="multi" id="MultiRow">
<tr><td>
<select name="store[product][]" required>
<option value="" selected="selected">-Product-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
<option value="19041">TRAVEL</option>
<option value="19063">HOUSEHOLD</option>
</select>
</td>
<!-- /Product selector -->
</table>
<input type="submit" value="ok">

Global If Else Statements

http://liveweave.com/EvfTww
I have two radio buttons one says div, and another says remove.
I add in some divs in html and when I select remove I want to be able to remove divs inside of #canvas when clicked.
The function provided below only works when divs are already visible when checked, but when I add new divs in the canvas from the code editor I also want to be able to remove those as well.
Any help is greatly appreciated.
HTML
<table id="main" border="1">
<tr>
<td id="canvas" valign="top"></td>
<td valign="top">
<div id="control_box">
<form id='tools'>
<input name="tool" id="tool-1" checked="checked" type="radio">
<label for="tool-1">DIV</label>
<input name="tool" id="tool-2" type="radio">
<label for="tool-2">Remove</label>
</form><br>
Border Width <select id="divborder">
<option value="1px">1px</option>
<option value="2px">2px</option>
<option value="3px" selected="selected">3px</option>
<option value="5px">5px</option>
<option value="7px">7px</option>
<option value="8px">8px</option>
<option value="9px">9px</option>
<option value="10px">10px</option>
</select><br>
Border Style <select id="divborderstyle">
<option value="dotted">dotted</option>
<option value="dashed">dashed</option>
<option value="solid" selected="selected">solid</option>
<option value="double">double</option>
<option value="groove">groove</option>
<option value="ridge">ridge</option>
<option value="inset">inset</option>
<option value="outset">outset</option>
</select><br>
Border Color
<input id="bcolor" type="text" name="bcolor" value="#f00" /></div><br>
BG Color
<input id="bgcolor" type="text" name="bgcolor" value="#000" onchange="window.set_fill_color(this.value); var col = this.value ; $('#colorSelectorFill').ColorPickerSetColor(col);" /></div>
<input type="button" id="nobg" value="none">
</div><br><br>
<textarea id='code' placeholder="The #canvas acts as page body"></textarea>
</td>
</tr>
</table>
JQuery/JavaScript
$('#tool-2').change(function() {
if ($(this).is(':checked')) {
alert('Remove Tool Chosen! You can now remove divs within the canvas.');
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
} else {
alert('Houston we have a problem!');
}
});
Try something like;
<input type="radio" name="test" value="div" checked> div
<input type="radio" name="test" value="remove"> remove
$("input[#name='test']").change(function(){
$("#parent_div_id").hide();
});
http://liveweave.com/lXdfqr
Using basically the same function as before, but this time I put it in another function called canvastools, and I removed the else statement as I do not need that for this experiment.
function canvastools(e) {
if ($('#tool-2').is(':checked')) {
$('#canvas div').on('click', function() {
$(this).remove();
code.val(preview.html());
});
}
}
I then call the function by stating that when the document is changed it will call the function.
$(document).change(function(e) {
canvastools(e);
});
I found that using the select element is a bit easier, however it's not exactly isolated. The remove tool's function will still apply even when a another tool/option is selected. I haven't figured out how to fix that problem just yet.
Here's the new fiddle/weave - http://liveweave.com/e5Efnc
function wrappertools(e) {
// Tools
$("select#tools").each(function() {
// DIV Tool
if ($(this).val() === 'div') {
$('#divoptions').show();
$('#spanoptions').hide();
// No Background Option
$('#nobg').click(function() {
$('input[name=bgcolor]').val('none');
});
var bcolor = $('input[name=bcolor]').val(),
bgcolor = $('input[name=bgcolor]').val(),
divborderstyle = $('#divborderstyle').val(),
divborder = $('#divborder').val();
alert('DIV Tool Selected!');
}
// Text Tool
if ($(this).val() === 'text'){
$('#spanoptions').show();
$('#divoptions').hide();
alert('Text Tool Selected!');
// No Background Option
$('#nospanbg').click(function() {
$('input[name=spanbgcolor]').val('none');
});
$('#addspantext').on('click', function() {
var spanbcolor = $('input[name=spanbcolor]').val(),
spanbgcolor = $('input[name=spanbgcolor]').val(),
spanborderstyle = $('#spanborderstyle').val(),
spanborder = $('#spanborder').val(),
spanfont = $('#spanfont').val(),
spancolor = $('#spancolor').val(),
spansize = $('#spansize').val(),
spantext = $('#spantext').val(),
placespan = $('<span style="position: relative; font-family: ' + spanfont + '; font-size: ' + spansize + '; font-color: ' + spancolor + '; border: ' + spanborder + ' ' + spanborderstyle + ' ' + spanbcolor + '; background: '+ spanbgcolor +';">' + spantext + '</span>');
$('.wrapper').append(placespan);
code.val(preview.html());
});
return false;
}
// Remove Tool
if ($(this).val() === 'remove') {
alert('Remove Tool Selected!');
$('#divoptions').hide();
$('#spanoptions').hide();
$('.wrapper div, .wrapper span').on('click', function() {
$(this).remove();
code.val(preview.html());
});
return false;
}
});
}
$(document).ready(function(e) {
wrappertools(e);
});
$(document).change(function(e) {
wrappertools(e);
});

jQuery Append UL with LI from DropDownList and Vice Versa

I have a dropdownlist with values. On a click of a button a unordered list gets appended with an <li> with details from the selected item in the dropdown list.
The <li> has an <a> tag in it which will remove the <li> from the <ul>.
I need to repopulate the dropdown list with the item removed from the <ul> when the <li> is removed.
Any ideas?
UPDATE:
Thanks for all your help. Here is my whole implementation:
<script type="text/javascript">
$(function() {
$("#sortable").sortable({
placeholder: 'ui-state-highlight'
});
$("#sortable").disableSelection();
$('#btnAdd').click(function() {
if (validate()) {
//Remove no data <li> tag if it exists!
$("#nodata").remove();
$("#sortable").append("<li class='ui-state-default' id='" + $("#ContentList option:selected").val() + "-" + $("#Title").val() + "'>" + $("#ContentList option:selected").text() + "<a href='#' title='Delete' class='itemDelete'>x</a></li>");
$("#ContentList option:selected").hide();
$('#ContentList').attr('selectedIndex', 0);
$("#Title").val("");
}
});
$('#btnSave').click(function() {
$('#dataarray').val($('#sortable').sortable('toArray'));
});
$('.itemDelete').live("click", function() {
var id = $(this).parent().get(0).id;
$(this).parent().remove();
var value = id.toString().substring(0, id.toString().indexOf('-', 0));
if ($("option[value='" + value + "']").length > 0) {
$("option[value='" + value + "']").show();
}
else {
var lowered = value.toString().toLowerCase().replace("_", " ");
lowered = ToTitleCase(lowered);
$("#ContentList").append("<option value='" + value + "'>" + lowered + "</option>");
}
});
});
function validate() {
...
}
function ToTitleCase(input)
{
var A = input.split(' '), B = [];
for (var i = 0; A[i] !== undefined; i++) {
B[B.length] = A[i].substr(0, 1).toUpperCase() + A[i].substr(1);
}
return B.join(' ');
}
</script>
<form ...>
<div class="divContent">
<div class="required">
<label for="ContentList">Available Sections:</label>
<select id="ContentList" name="ContentList">
<option value="">Please Select</option>
<option value="CHAN TEST">Chan Test</option>
<option value="TEST_TOP">Test Top</option>
</select>
<span id="val_ContentList" style="display: none;">*</span>
</div>
<div class="required">
<label for="ID">Title:</label>
<input class="inputText" id="Title" maxlength="100" name="Title" value="" type="text">
<span id="val_Title" style="display: none;">*</span>
</div>
<input value="Add Section" id="btnAdd" class="button" type="button">
</div>
<ul id="sortable">
<li class="ui-state-default" id="nodata">No WebPage Contents Currently Saved!</li>
</ul>
<div>
<input type="submit" value="Save" id="btnSave" class="button"/>
</div>
<input type="hidden" id="dataarray" name="dArray" />
</form>
You've acknowledged that you know very little about jQuery, so let's look at some of this piece by piece. This snippets will give you the information you need to construct your solution.
Adding click-events is relatively easy:
$("#myButton").click(function(){
/* code here */
});
Removing elements is also pretty simple:
$("#badThing").remove();
The thing about .remove() though is that you can add it elsewhere after removing it:
$("#badThing").remove().appendTo("#someBox");
That moves #badThing from wherever it was, to the inside of #someBox.
You can add new list items with the append method:
$("#myList").append("<li>My New Item</li>");
You can get the selected item of a drop-down like this:
var item = $("#myDropDown option:selected");

Categories