Jquery onclick this remove both of span - javascript

how to do that when i Click to "OnClick" will remove City1 and City2
I mean want to remove both of them by one click.
Waiting for your reply
thanks.
<select multiple="multiple" id="city" >
<option value="First" >First</option>
<option value="Second" >Second</option>
<option value="Third" >Third</option>
</select>
<div id="City1" ></div>
<div id="City2" ></div>
$(document).ready(function()
{
var i = 0;
$("#city").click(function(){
var sel=$(this).val();
i++;
$('#City1, #City2').append('<span id="'+ [i] +'"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;" onclick="$(this).remove();">'+ sel +'</span>');
});
});
http://jsfiddle.net/zeynaloffnet/WRs86/2/

I know you've got your answer already, but I thought it might be worth pointing out a few things.
When creating DOM elements, you might consider using the object literal syntax, where you create the element as usual, then add its properties using key/value pairs:
$('<div'>, { class: 'myDiv'});
Ids cannot start with a number. It might be worth appending the option's value to a prefix instead:
id: "opt-" + this.value,
It's a good idea to give your new span a specific class , then alter its appearance by targeting it from a separate style-sheet. This will remove the need for all that ugly and hard to maintain, inline CSS.
These changes would give you something like:
span {
border-radius:5px;
color:#fff;
background-color:#005e3a;
padding:5px;
cursor:pointer;
width:auto;
}
<select multiple="multiple" id="mySelect">
<option value="First">First</option>
<option value="Second">Second</option>
<option value="Third">Third</option>
</select>
<div id="result"></div>
$("#mySelect").click(function () {
var span = $("<span />", {
id: "opt-" + this.value.toLowerCase(),
class: "city",
text: this.value,
click: function () {
$(this).remove();
}
});
$('#result').html(span);
});
Here's a fiddle
EDIT:
Here's how you'd do it with two elements:
$("#mySelect").click(function () {
var span1 = $("<span />", {
class: "opt-" + this.value.toLowerCase(),
text: this.value,
click: function () {
$(this).remove();
}
}),
span2 = span.clone(true);
$('#result').empty().append(span1).append(span2);
});
You have to clone the original span, as append actually moves the element, so appending it twice wouldn't work.
New fiddle
I also changed the id attribute to class, as ids should be unique to a page.

You just need to clean the div before. Use .empty() before .append()
<select multiple="multiple" id="city" >
<option value="First" >First</option>
<option value="Second" >Second</option>
<option value="Third" >Third</option>
</select>
<div id="City1" ></div>
<div id="City2" ></div>
$(document).ready(function()
{
var i = 0;
$("#city").click(function(){
var sel=$(this).val();
i++;
$('#City1, #City2').empty().append('<span id="'+ [i] +'"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;" onclick="$(this).remove();">'+ sel +'</span>');
});
});
http://jsfiddle.net/guinatal/WRs86/3/

onClick="removeCity();"//add this as your onlick
var removeCity = function()
{
$("#City1").remove();
$("#City2").remove();
}

As per my understaning, Here is your updated fiddle: http://jsfiddle.net/kailashyadav/WRs86/7/
$(document).ready(function () {
var i = 0;
$("#city").click(function () {
var sel = $(this).val();
i++;
$('#City1, #City2').append('<span class="spanClass" id="' + [i] + '"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;" onclick="$(\'.spanClass\').remove();">' + sel + '</span>');
});
});

Demo Fiddle
If you want to replace the contents..simply change append to html
$('#City1, #City2').html('<span id="' + [i] + '"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;">' + sel + '</span>');
To remove both span elements when only clicking one or the other, take the onclick function out and replace with
$('#City1 span, #City2 span').on('click',function () {
$('#City1 span, #City2 span').remove();
});

Related

How to remove an incremental element in HTML using JavaScript

So I want to create a function that will let me add/remove an element in the HTML, I'm already done with the "add" part that increments the id value onchange (example: id=tag1, id=tag2, etc). My problem is on the "remove" part, I don't know how to put an incremental value inside onclick=remove_tag(). Here's my code
function update() {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
let counter = 0;
document.getElementById("textarea").innerHTML += "<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal + "<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag('tag"+ counter +"');></button></span></li></div>";
$("#textarea div").each(function(i){this.id = "tag" + (i + 1)})
}
function remove_tag(id) {
document.getElementById(id).innerHTML = "";
}
What I want to do is to make my onclick on the button to be (onclick="remove_tag1", onclick="remove_tag2", onclick="remove_tag3", etc). Sorry for the question, still a newbie in JavaScript. Thanks for the help. Here's an image https://pasteboard.co/k7hb7cVHSQHj.png
<div class="resume-skill-item">
<h5>
<ul class="list-inline">
<div align="right">
<select id="skill_tags" onchange="update()">
<option selected="true" disabled="disabled">*Select All That Applies</option>
<option value="mechanic">Mechanic</option>
<option value="appliance_repairer">Appliance Repairer</option>
<option value="carpenter">Carpenter</option>
<option value="plumber">Plumber</option>
<option value="technician">Technician</option>
</select>
</div>
</ul>
<div id="textarea" class="large-single-textarea">
</div>
</h5>
</div>
```
You can use data attribute on delete button to keep reference on added items when you want to delete them.
function update(e) {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
let counter = 0;
document.getElementById("textarea").innerHTML +=
`<div class="tags_inline" id="${e.value}"><li class="list-inline-item"><span class="badge badge-dark">"${selVal}"<button data-select-id="${e.value}" class="fa fa-times-circle text-white" id="delete" onclick=remove_tag(this) >remove</button></span></li></div>`;
}
function remove_tag(e) {
document.getElementById(e.dataset["selectId"]).remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resume-skill-item">
<h5>
<ul class="list-inline">
<div align="right">
<select id="skill_tags" onchange="update(this)">
<option selected="true" disabled="disabled">*Select All That Applies</option>
<option value="mechanic">Mechanic</option>
<option value="appliance_repairer">Appliance Repairer</option>
<option value="carpenter">Carpenter</option>
<option value="plumber">Plumber</option>
<option value="technician">Technician</option>
</select>
</div>
</ul>
<div id="textarea" class="large-single-textarea">
</div>
</h5>
</div>
You can do it by sending the element itself thru args to the remove_tag function:
function update() {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
//add tag with a remove_tag(this) onclick action
document.getElementById("textarea").innerHTML +=
"<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal +
"<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag(this);></button></span></li></div>";
}
Then by DOM tree we can access and remove the element.
The DOM tree for this looks like div > li > span > button
The click event is triggered on the button so the function will look like this:
function remove_tag(element) {
//Here we grab the node that tag is on at the DOM tree
let tag = element.parentNode.parentNode;
//Same with the father div
let div = tag.parentNode;
//Then from that div we remove the selected element
div.removeChild(tag);
}
I recommend you to read more about the DOM

Cloning div on click breaks when moving the button out of container?

I found this nifty js fiddle and it does nearly exactly what I need
However its cloning the parent of the button and id like to have the button separate from the actual div being cloned. (if you put the clone button back into the container with the remove button it works fine again)
In all I am trying to accomplish 3 things.
1. Have the button outside of the div that's being duplicated (1 button)
2. Limit the number of duplication's to a total of 6. (or any changeable variable)
3. Update the <h4> content and change the number 1 to the next number. ie: (1-6)
I'm not very JS savvy although I do dabble. If anyone has the time to help me figure out the above it would be beyond appreciated! Here's the JS FIDDLE I've been playing with.
Thanks!
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
I think the folowing is what you're trying to acheive, you have to add another variables cloned_nbr and clones_limit to control the cloned divs:
var cloneIndex = 1;
var clones_limit = 4;
var cloned_nbr = $(".clonedInput").length-1; //Exclude Default (first) div
function clone()
{
if(cloned_nbr<clones_limit)
{
cloneIndex++;
cloned_nbr++;
var new_clone = $(".clonedInput").first().clone();
new_clone.attr("id", "clonedInput" + cloneIndex);
new_clone.find(".label-nbr").text(cloneIndex);
new_clone.find(".category").attr("id","category"+cloneIndex);
new_clone.find(".remove").attr("id","remove"+cloneIndex);
new_clone.on('click', 'button.clone', clone);
new_clone.on('click', 'button.remove', remove);
$(".clone").before(new_clone);
}
}
function remove(){
if(cloneIndex>1){
$(this).parents(".clonedInput").remove();
cloned_nbr--;
}
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
body { padding: 10px;}
.clonedInput { padding: 10px; border-radius: 5px; background-color: #def; margin-bottom: 10px; }
.clonedInput div { margin: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="label-nbr">1</span><span class="requiredField">*</span></label>
<select class="category" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div class="actions">
<button class="remove">Remove</button>
</div>
</div>
<button class="clone">Clone</button>
You can select the last occurence of .clonedInput and clone that, then insert it after the original element:
var regex = /^(.+?)(\d+)$/i;
function clone(){
var cloneIndex = $(".clonedInput").length + 1;
if (cloneIndex > 6) return;
$source = $(".clonedInput").last();
$source.clone()
.insertAfter($source)
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.remove', remove)
.find('label').html('Learning category ' + cloneIndex + ' <span class="requiredField">*</span>');
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category 1 <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div class="actions">
<button class="remove">Remove</button>
</div>
</div>
<button class="clone">Clone</button>
I'd initialize plain block as template and use it as clone base.
HTML
<div class="box-wrap">
<button class="clone">Clone</button>
</div>
Full demo: http://jsfiddle.net/jeafgilbert/tfFLt/1898/

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 clone form fields and increment id

I have a block of form elements which I would like to clone and increment their ID's using jQuery clone method. I have tried a number of examples but a lot of them only clone a single field.
My block is structured as such:
<div id="clonedInput1" class="clonedInput">
<div>
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
</div>
Obviously elements are lined up a lot better but you get the idea.
I would like to keep the id structure i.e. category1, subcategory1 etc as I use these to dynamically display select options based on the parent selection so if its possible to have each cloned block like category1/category2/category3 etc that would be great.
HTML
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
JavaScript - Jquery v1.7 and earlier
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
$("button.clone").live("click", function(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
There is only one silly part :) .attr("id", "clonedInput" + $(".clonedInput").length) but it works ;)
JAvascript - JQuery recent (supporting .on())
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
working example here
Another option would be to use a recursive function:
// Accepts an element and a function
function childRecursive(element, func){
// Applies that function to the given element.
func(element);
var children = element.children();
if (children.length > 0) {
children.each(function (){
// Applies that function to all children recursively
childRecursive($(this), func);
});
}
}
Then you can make a function or three for setting the attributes and values of your yet-to-be-cloned form fields:
// Expects format to be xxx-#[-xxxx] (e.g. item-1 or item-1-name)
function getNewAttr(str, newNum){
// Split on -
var arr = str.split('-');
// Change the 1 to wherever the incremented value is in your id
arr[1] = newNum;
// Smash it back together and return
return arr.join('-');
}
// Written with Twitter Bootstrap form field structure in mind
// Checks for id, name, and for attributes.
function setCloneAttr(element, value){
// Check to see if the element has an id attribute
if (element.attr('id') !== undefined){
// If so, increment it
element.attr('id', getNewAttr(element.attr('id'),value));
} else { /*If for some reason you want to handle an else, here you go*/ }
// Do the same with name...
if(element.attr('name') !== undefined){
element.attr('name', getNewAttr(element.attr('name'),value));
} else {}
// And don't forget to show some love to your labels.
if (element.attr('for') !== undefined){
element.attr('for', getNewAttr(element.attr('for'),value));
} else {}
}
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined){
element.val('');
}
}
Then add some markup:
<div id="items">
<input type="hidden" id="itemCounter" name="itemCounter" value="0">
<div class="item">
<div class="control-group">
<label class="control-label" for="item-0-name">Item Name</label>
<div class="controls">
<input type="text" name="item-0-name" id="item-0-name" class="input-large">
</div>
</div><!-- .control-group-->
<div class="control-group">
<label for="item-0-description" class="control-label">Item Description</label>
<div class="controls">
<input type="text" name="item-0-description" id="item-0-description" class="input-large">
</div>
</div><!-- .control-group-->
</div><!-- .item -->
</div><!-- #items -->
<input type="button" value="Add Item" id="addItem">
And then all you need is some jQuery goodness to pull it all together:
$(document).ready(function(){
$('#addItem').click(function(){
//increment the value of our counter
$('#itemCounter').val(Number($('#allergyCounter').val()) + 1);
//clone the first .item element
var newItem = $('div.item').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#itemCounter').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
}
);
// Finally, add the new div.item to the end
newItem.appendTo($('#items'));
});
});
Obviously, you don't necessarily need to use recursion to get everything if you know going in exactly what things you need to clone and change. However, these functions allow you to reuse them for any size of nested structure with as many fields as you want so long as they're all named with the right pattern.
There's a working jsFiddle here.
Clone the main element, strip the id number from it.
In the new element replace every instance of that id number in every element id you want incremented with the new id number.
Ok, here's a quicky code here.
Basically, this part is the most important:
(parseInt(/test(\d+)/.exec($(this).attr('id'))[1], 10)+1
It parses the current id (using RegEx to strip the number from the string) and increases it by 1. In your case instead of 'test', you should put 'clonedInput' and also not only increase the value of the main element id, but the three from the inside as well (category, subcategory and subsubcategory). This should be easy once you have the new id.
Hope this helps. :)
Add data attribute to the input to get the field name, increment the value with variable.
html :
<td>
<input type="text" data-origin="field" name="field" id="field" required="" >
<div role="button" onclick='InsertFormRow($(this).closest("tr"),"tableID","formID");' id="addrow"> + </div>
</td>
and put this javascript function
var rowNum = 1;
var InsertFormRow = function(row, ptable, form)
{
nextrow = $(row).clone(true).insertAfter(row).prev('#' + ptable + ' tbody>tr:last');
nextrow.attr("id", rowNum);
nextrow.find("input").each(function() {
this.name = $(this).data("origin") + "_" + rowNum;
this.id = $(this).data("origin") + "_" + rowNum;
});
rowNum++;
}

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