javascript/jquery remove or delete option from select - javascript

I need to delete an option from a select in certain circumstances.
Basically:
if(mystatement == true)
{
//remove item with id 'option1' from select of id 'select1'
}
Anyone know the code for me to achieve this?
Many thanks.

Remove by Value:
$("#select1 option[value=1]").remove();
Remove by Text:
$("#select1 option:contains(Text)").remove();

Edit
Since id is unique in the document no need to relate it to the parent select element. You can do simply
$("#option1").remove();

jQuery:
$("#option1").remove();
or
$("#select").remove("#option1");
And the classic javascript method:
var option1 = document.getElementById("option1");
document.getElementById("select1").removeChild(option1);

I have seen many people with this problem. I have created this script that could be useful. Hope you like it:
var robable = {
init: function() {
robable.get_selected_option_from_select();
},
get_selected_option_from_select: function() {
$(".robable").off().on("change", function() {
if ($(this).val() !== "") {
robable.add_to_list($(this));
}
});
},
remove_option_from_select: function(select_id, value) {
$("#" + select_id + " option[value='" + value + "']").remove();
},
add_option_to_select: function(select_id, value, text) {
$('#' + select_id).append('<option value="' + value + '">' + text + '</option>');
},
add_to_list: function(select) {
option_text = $(".robable option[value='" + select.val() + "']").text();
//Add to list
$('#list').append("<li data-value='" + select.val() + "' data-text='" + option_text + "'><a href='#' class='filter-remove' data-parent-id='" + select.attr("id") + "'>Delete</a> " + option_text + "</li>");
robable.remove_from_list();
//Remove from select
robable.remove_option_from_select(select.attr("id"), select.val());
},
remove_from_list: function() {
$(".filter-remove").off().on("click", function() {
var select_id = $(this).data('parent-id');
var option_value = $(this).closest("li").data('value');
var option_text = $(this).closest("li").data('text');
//Add to select
robable.add_option_to_select(select_id, option_value, option_text);
//Remove from list
$(this).closest("li").remove();
});
}
};
robable.init();
<!DOCTYPE html>
<html>
<head>
<title>Select Robables</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<ul id="list"></ul>
</body>
</html>

Related

Dropdown won't select and open div... What am I doing wrong?

On our Offices page if you click the dots on the map it opens a div below and changes the sidebar contents. We added a dropdown so you could select cities on mobiles. Since I recreated the website and copied over the code I've done something and it doesn't work anymore.
I know the problem has something to do with this bit of code
$('#continent').change(function() {
$('.targetDiv').hide();
$('#worldwide').hide();
var target = $("select option:selected").attr('target');
var value = $("select option:selected").attr('value');
console.log($('#' + value));
$(".detail-container").empty();
$('#' + value).clone().show().appendTo(
".detail-container");
$('#div' + target).show();
if (value == "worldwide") {
$('.slidingDiv').slideUp();
}
});
Here is the full code
jQuery(function($) {
$(".dot").show();
$('.dot').click(function() {
$(".slidingDiv").slideDown('slow');
});
$('#continent').change(function() {
$(".slidingDiv").slideDown('slow');
});
});
jQuery(function($) {
$('#showSingle').click(function() {
$('.targetDiv').show();
});
$('.dot').click(function() {
$('.targetDiv').hide();
$('#div' + $(this).attr('target')).show();
var value = $(this).attr('city');
$(".detail-container").empty();
$('#' + value).clone().show().appendTo(
".detail-container");
$('#' + value).show();
$('#continent').val(value);
});
$('#continent').change(function() {
$('.targetDiv').hide();
$('#worldwide').hide();
var target = $("select option:selected").attr('target');
var value = $("select option:selected").attr('value');
console.log($('#' + value));
$(".detail-container").empty();
$('#' + value).clone().show().appendTo(
".detail-container");
$('#div' + target).show();
if (value == "worldwide") {
$('.slidingDiv').slideUp();
}
});
});
I'm sure this is something simple for someone who knows Javascript.
Thanks.
There you go:
$('#continent').change(function() {
$('.targetDiv').hide();
$('#worldwide').hide();
var target = $("#continent").find(":selected").attr('target');
var value = $("#continent").val();
console.log($('#' + value));
$(".detail-container").empty();
$('#' + value).clone().show().appendTo(
".detail-container");
$('#div' + target).show();
if (value == "worldwide") {
$('.slidingDiv').slideUp();
}
});
Should work, but it's very ugly code i guess :P

Getting values of inputs generated using jQuerys html() function

I have a page with a table and when I click edit I change the table elements into inputs using jQuerys html() function.
I then want to have the user edit the values of the inputs and save these to database, problem is when I try and grab the data I get undefined for all the inputs that are created with the html() function.
I am sure it is something to do with this.. Any help would be great! Here is my code:
$('[name="edit"]').click(function(e) {
e.preventDefault();
var data = {
'invoice_number': $(this).attr('data-invoice-number'),
'count': $(this).attr('data-count')
};
var description_text = $('[data-description-' + data.count).text();
var rates_text = $('[data-rates-' + data.count).text();
var quantity_text = $('[data-quantity-' + data.count).text();
console.log(description_text);
$('[data-description-' + data.count + ']').html('<input type="text" name="description" value="' + description_text + '" />');
$('[data-rates-' + data.count + ']').html('<input type="text" name="rates" value="' + rates_text + '" />');
$('[data-quantity-' + data.count + ']').html('<input type="text" name="quantity" value="' + quantity_text + '" />');
$(this).css('display', 'none');
$('[name="save"][data-count=' + data.count + ']').css('display', 'inline-block');
$('[name="cancel"][data-count=' + data.count + ']').css('display', 'inline-block');
});
$('[name="save"]').unbind().bind().click(function(e) {
e.preventDefault();
var data = {
'invoice_number': $('[name="save"]').attr('data-invoice-number'),
'description': $('[name="description"]').val(),
'rates': $('[name="rates"]').val(),
'quantity': $('[name="quantity"]').val(),
};
console.log(data); // this outputs undefined for values above generated using html() method
if (data.description == '') {
append_alert('danger', 'Please enter a <b>Description</b>');
} else if (data.rates == '') {
append_alert('danger', 'Please enter your <b>Rates</b>');
} else if (data.quantity == '') {
append_alert('danger', 'Please enter a <b>Quantity</b>');
} else {
$.post('edit_invoice_item', data, function() {}).done(function() {
append_alert('success', 'Item Edited!');
setTimeout(function() {
location.reload();
}, 2000)
});
}
});
Regards
For dynamically added elements use event delegation
Change
$('[name="edit"]').click(function(e) {
To
$(document).on('click', '[name="edit"]', function(e) {
AND
$('[name="save"]').unbind().bind().click(function(e) {
To
$(document).on('click', '[name="save"]', function(e) {

Using variable to add and remove a form input field with jQuery

I am trying to add a hidden input field to a form when a span with class="checkbox" is clicked, and remove that same field when span with checkmark is clicked.
I am able to add the input, but I cannot remove it.
My HTML:
<span title="Here's My Title" class="wishlistcheck checkbox">1</span>
<form id="wishlistform"></form>
My Javascript:
$(document).ready(function() {
var appNum = 0;
$("span.wishlistcheck").click(function() {
var el = $(this);
var appName = el.attr("title");
var isChecked = el.hasClass('checkmark');
if(!isChecked) {
el.removeClass('checkbox');
el.addClass('checkmark');
appNum++
$("#wishlistform").append("<input id=\"" + appName + "\" type=\"hidden\" name=\"product_" + appNum + "\" value=\"" + appName + "\">");
} else {
el.removeClass('checkmark');
el.addClass('checkbox');
appNum--
$("input#" + appName).remove();
}
});
});
I guess you have to put the appNum-- after the .remove() method calling. Try it:
$(document).ready(function() {
var appNum = 0;
$("span.wishlistcheck").click(function() {
var el = $(this);
var appName = el.attr("title");
var isChecked = el.hasClass('checkmark');
if(!isChecked) {
el.removeClass('checkbox');
el.addClass('checkmark');
appNum++
$("#wishlistform").append("<input class=\"" + appName + "\" type=\"hidden\" name=\"product_" + appNum + "\" value=\"" + appName + "\">");
} else {
el.removeClass('checkmark');
el.addClass('checkbox');
appNum--
$("input[class=" + appName + "]").remove();
}
});
});
You probably have multiple DOM elements by that id tag, and so it may be removing an element matching that id but not the right one.
Try giving it a class name instead and getting more specific in your jQuery parameters by adding parent elements, i.e.
$('#wishlistform input#' + appName).remove();

How to attach click event at runtime when i have all ids in an array that gets populated when document is ready?

I have the following code,
<script type="text/javascript">
$(document).ready(function () {
var dataAnalysisDataFileTableIDs = $("#dataAnalysisDataFileTable tr[id]").map(function () { return this.id; }).get();
//for(var key in dataAnalysisDataFileTableIDs) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//}
//$.each(dataAnalysisDataFileTableIDs, function (index, value) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//});
$("#dataAnalysisDataFileTable tr[id]").each(function (i, elem) {
$(elem).click(function () { alert("[" + i + "][" + this.id + "]"); });
});
$("#aaa").click(function () {
alert("meow");
});
});
</script>
and it doesn't work i also tried the one in the comments section which does the same as "for in" it doen't work but when i attach click to the id #aaa it works fine how do i approach this problem when i have all the ids in the array and i want to be able to attach events to them?
How about just using each ? Like so:
<html>
<head><script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script></head>
<body>
<table id="dataAnalysisDataFileTable">
<tr id="foo"><td>foo</td></tr>
<tr id="bar"><td>bar</td></tr>
</table>
<script type="text/javascript">
$(document).ready(function () {
$("#dataAnalysisDataFileTable tr[id]").each(function(i, elem) {
$(elem).click(function() { alert("[" + i + "][" + this.id + "]") } );
});
});
</script>
</body>
</html>
I've patched the possible errors. I cannot resolve the value variable though.
for(var index=0, length=dataAnalysisFileTableIDs.length; index++) {
var key = dataAnalysisFileTableIDs[index];
var id = "#" + dataAnalysisFileTableIDs[key];
$(id).click(function () {
/* Value ? It's not defined*/
alert("[" + index + "][" + /*value +*/ "]");
});
}
dataAnalysisFileTableIDs is an array. To loop through an array, you have to use the for ( init_index ; condition ; increment ) loop. The key can be obtained through name_of_array[index].

jQuery replace div based on rel attribute

I'm trying to replace a div based on a class name and a rel attribute.
<script type="text/javascript">
$(function () {
$('.special_button').click(function () {
var num = $(this).attr('rel');
$(button with class .value_button and rel=num).replaceWith("<div class='value_button' >" + $(this).val() + "</div>");
$('div.content_slide').slideUp(600);
});
});
</script>
How would you do this?
Try this:
$(function () {
$('.special_button').click(function () {
var num = $(this).attr('rel');
$('.value_button[rel="' + num + '"]').replaceWith("<div class='value_button' >" + $(this).val() + "</div>");
$('div.content_slide').slideUp(600);
});
});

Categories

Resources