I'm pretty new to JQuery, as you can tell by my question...
The user can append many new input fields to the form. This works great, but how can they delete a specific field? If they append 5 input fields, how do they delete lets say the third field?
Below is my following code. What is currently does is always delete the first item when clicked.
$("#addNewItem").click(function(){
$("#invoice_items").append('<input type="text" name="name[]" value="name" id="item_name" class="item_name" /><img src="images/delete.png" />');
});
$("#delete_input").live("click", function(){
$("#item_name").remove();
$(this).remove();
});
How about using additional container for inputs?
http://jsfiddle.net/dFpMV/
$("#addNewItem").click(function(){
$("#invoice_items").append('<div class="input-container"><input type="text" name="name[]" value="name" id="item_name" class="item_name" />X<img src="images/delete.png" /></div>');
});
$("#delete_input").live("click", function(){
$(this).parent().remove();
});
First, count the number of inputs you've added and store it in a variable.
Then, when you add the element, make a unique identifier based on that number.
$("#invoice_items").append('<input type="text" name="name[]" value="name" id="item'+count'" class="item_name" /><img src="images/delete.png" />');
I would avoid using the specific item name as the id in this case, use something generic like item0, item1 etc.
Then, to remove
$("#item" + desiredNumber).remove();
$(this).remove();
all links need to have unique id. Allowing to append element with specified id twice is an error. What you could do is to add an artificial number at the end of id to make them unique. I would wrap both input and link into a div, i would assign an unique id to it, assign a class to delete link instead of id and remove div like ($this).parent().remove()
If you are using jQuery 1.7+: Also note that .live() is deprecated and you should use .on() instead (note that syntax is however a little bit different).
I made 2 examples for you and adding a dummy variable so you can see whats happend:
1 If you know how to DOM will look like and the relationship between the delete link and the input you can simply traversing to the previous item.
$("#delete_input").live("click", function(){
$(this).prev().remove();
$(this).remove();
});
http://jsfiddle.net/JgKRw/ Example nr 1 in action
2 You give each item a unique number when you add them to the DOM.
var dummyId = 0;
$("#addNewItem").click(function(){
dummyId++;
$("#invoice_items").append('<input type="text" name="name[]" value="name ' + dummyId + '" id="item_name" class="item_name" data-id="' + dummyId + '" /><a data-id="' + dummyId + '" href="#" id="delete_input">' + dummyId + '<img src="images/delete.png" /></a>');
});
$("#delete_input").live("click", function(){
var deletedId = $(this).data("id"); // Get the ID of the clicked link
$("input[data-id='" + deletedId + "']").remove(); // Seach for an input which has the ID
$(this).remove();
});
http://jsfiddle.net/JgKRw/1/ Example nr 2 in Action
I would implemented number 2, couse else you have to take care of the script if you want to change the UI.
Btw you should only have one element assigned to an ID, so change your ID and use classes insteed.
http://api.jquery.com/class-selector/
Given the markup you appending it should be simply $(this).prev().remove(); and ignore the IDs.
Here's my fiddle:
http://jsfiddle.net/JfUAa/
(function () {
var count = 0,
items = document.getElementById("input_items"),
$items = $(items),
tpl = '<div><input type="text" id="{{id}}" />delete</div>';
function addItem(){
$items.append(tpl.replace("{{id}}", count++));
}
function remove(){
items.removeChild(this.parentNode);
}
$("#addNewItem").click(addItem);
$items.on("click", "a", remove);
}());
Related
I am trying to collect multiple pieces of data from a checkbox, but I am unsure of how to do this. Right now I have:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" style="display:inline-block;">
Which allows me to collect an id (contained in {{$friend}}) that I need. But I also need the name associated with this id. Is there a way to collect multiple values from a single checkbox? I would need this because I am collecting the data and moving to another form without changing the view. This would be used for javascript which would print out stuff in the view as it is checked (i.e. the id and name).
Here is the javascript:
<script>
$(document).ready(function(){
var callbacks_list = $('.callbacks ul');
$('.facebook-friends-larger input').on('ifChecked', function(event){
callbacks_list.prepend('<li><img src="https://graph.facebook.com/'+this.id+'/picture" alt="" height="50" width="50"><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');
});
$('.facebook-friends-larger input').on('ifUnchecked', function(event) {
callbacks_list.find('span#'+ this.id).closest('li').remove();
console.log(this.id);
});
});
</script>
Any ideas? Thank you for your help.
Try this this will be helpyou..
$("input[type=checkbox]").change(function(){
alert($(this).val()); //get a val
alert($(this).attr('name')); //get a value of name attribute
});
Fiddle here
If you have the access to the username before the page is loaded (and is therefore able to inject it into the DOM without making ajax queries after pageload or user action), you can store them in HTML5 data- attributes, for example, data-name in the following format:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" data-name="{{name}}" style="display:inline-block;">
You can access the name by simply calling the .data() method in jQuery, i.e. $('input').data('name').
Use:
var name = $("#checkbox-id").attr("name"); // Use whatever method you have to target the checkbox
and so on to get the other values
Try this
HTML
<input tabindex="1" type="checkbox" name="friend[]" id="123" value="{{$friend}}" style="display:inline-block;">test
JS
$(document).ready(function(){
$("#123").change(function(){
$(this).val(); //get a val
console.log($(this).attr('name')); //get a value of name attribute
});
});
FIDDLE
I want to get "The walking dead" also but it only gets the first hidden. Can i put a class on .this or how should I do?
$(".articel input[type='button']").click(function(){
var price = $(this).siblings("input[type='hidden']").attr("value");
var quantity = $(this).siblings("input[type='number']").attr("value");
var name = $(this).siblings("input[type='hidden']").attr("value");
var ul = document.getElementById("buylist");
var prod = name + " x " + quantity + " " + price + "$";
var el = document.createElement("li");
el.innerHTML = prod;
ul.appendChild(el);
<form class="articel">
Quantity: <input type="number" style="width:25px;"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30">
<input type="hidden" value="The walking dead">
</form>
The conventional way to identify form fields is by the name property.
HTML:
<input type="hidden" name="title" value="The walking dead">
jQuery:
var name = $(this).siblings('input[name=title]').val();
Your current selector, siblings("input[type='hidden']"), selects all hidden field siblings, but since you have no way to discern them, attr will always just yield the value of the first match.
You could also have iterated over your collection of elements, or accessed them by index siblings('input[type=hidden]:eq(1)') or siblings('input[type=hidden]').eq(1), for instance, but it is a poor design that will break your code if you add another hidden field for something else. You really should prefer to name your elements so that you can access them in a meaningful way and know your data. That way you'll be free to move around and modify your markup according to new requirements, without breaking your script.
By the way, I'm using .val() above, which is shorthand for .attr('value').
One option is to use special selectors, e.g. :first and :last:
var price = $(this).siblings("input[type='hidden']:first").attr("value");
var name = $(this).siblings("input[type='hidden']:last").attr("value");
However, you always can set a class name to the elements:
<input type="hidden" class="price" value="30">
<input type="hidden" class="name" value="The walking dead">
var price = $(this).siblings(".price").attr("value");
var name = $(this).siblings(".name").attr("value");
I would add an class name to your hidden inputs (price, name). This way the html source code is more readable and also the js code will be more readable.
I'm creating checkboxes using JQuery as following:
$('<input type="checkbox" ' + 'id=' + (i+1) + '>' + (i+1) + '</input><br/>')
Then later it is removed whenever the user checks the box in:
if (this.checked) {
$(this).remove();
}
However, The input box is deleted, but the number (id) stays on the page, along the <br/> Tag, so I can see the #i there on the HTML Page.
I would like to remove them as well.
So, to in order to make my question as complete as possible, here is how the HTML is laid:
<input id="1" type="checkbox">
1
<br>
Could someone please give me a clue how to remove #i and <br/> from the page?
Thanks
as stated by other answers - input don't have closing tags
You will still need to remove all id and <br />. You can find those with .next() function in jquery. You should put your id in <label> or <span>.
Then. for example:
$(this).next('label').remove();
$(this).next('br').remove();
$(this).remove();
Code can be written shorter but it's for you to see how it works.
The text in <input> text boxes is not set with a textnode (like for textareas), but with the value attribute. (Sorry for the confusion)
Yet, you want to have a checkbox. Best, create a <label> for it, instead of a text node plus a <br /> (which is not handleable with jQuery):
<div class="inputcell">
<input type="checkbox" id="check5">
<label for="check5">5</label>
</div>
With this DOM, you can easily remove the whole box by $("#check5").parent().remove(). Note that single numbers are no valid element ids.
that's because input tags don't have closing tags and remove ignores everything after the >, change this:
$('<input type="checkbox" ' + 'id=' + (i+1) + '>' + (i+1) + '</input><br/>')
to:
$('<input type="checkbox" ' + 'id=' + (i+1) + 'value="' + (i+1) +'"><label>'+ (i+1) +'</label>')
$(this).next('label').andSelf().remove();
input tags don't have closing tag, to create a checkbox you just need the following:
$('<input type="checkbox" ' + 'id=' + (i+1) + '>');
and if you want also to use a label for that checkbox, create appropriate label or any other element, because you can't put closign tag for input and a text between them
I wanna implement this using jquery instead of inline but Its not working, inline works fine. The other reason I wanna use jquery is if user selects more than one checkbox, the url should be appended with whatever is already there + OR '2nd CheckBox Value' like this:
"http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office OR Hospital"
The space infront and following OR is fine..
How can I achieve this? Can someone help me out?
Offices<input name="LocType" type="checkbox"
value="Office" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office'; return true;">
Hospitals<input name="LocType" type="checkbox"
value="Hospital" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Hospital'; return true;">
Facilities<input name="LocType" type="checkbox"
value="Facility" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Facility'; return true;">
Bind to the change event on the checkboxes. When clicked read the current checkbox value and then all other relative checkboxes. Append your base url with your custom query string and go crazy. :)
This isn't tested but hopefully it's a good starting point.
var baseUrl = 'http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ' OR ' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
You can try this.
HTML
<input name="LocType" type="checkbox" value="Office" />
<input name="LocType" type="checkbox" value="Hospital" />
<input name="LocType" type="checkbox" value="Facility" />
JS
Assuming you have a button or something on click of which you want to create a url with all the checked LocType checkbox values appended to the url seperated by OR
var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('button').click(function(){
//This will get the array containing values of checked LocType checkboxes
var checkedLocTypeValues = $('input[name=LocType]:checked').map(function(){
return this.value;
});
//Use Array.join() method to join the array elements by " OR "
url = url + "&k=" + checkedLocTypeValues.join(" OR ");
//Now you can use url variable which has all the checked LocType checkboxes value
}
jQuery map() reference - http://api.jquery.com/jQuery.map/
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="'(+ this.value = ''; +)'" value="Enter Choice #' + i + '"/></p>')
I'm not sure if this is the correct syntax or not, but whatever I am using is not working. ANy help? Thanks
HTML:
<input type="text" class="class-1" value="Enter Choice #1">
<input type="text" class="class-2" value="Enter Choice #2">
JQUERY:
$(document).ready(function() {
$('input[class^="class-"]').focus(function() {
var $input = $(this);
if($input.val() == $input.data('default_val') || !$input.data('default_val')) {
$input.data('default_val', $input.val());
$input.val('');
}
});
$('input[class^="class-"]').blur(function() {
var $input = $(this);
if ($input.val() == '') $input.val($input.data('default_val'));
});
});
Above code clear the value when the textfields gets focus and adds the default value when textfield is empty on lost focus (blur).
Updated fiddle: http://jsfiddle.net/K3Sx7/4/
EDIT: updated code to conform question.
Add an id to your input field:
<input id="myinput"...
Then add this code in your $(document).ready(... call:
$('#myinput') // get element whose id is 'myinput'
.click(function() { // bind a click handler
$(this).val('') // clear field
.unbind('click'); // unbind click handler to avoid field being cleared again
})
I think you can do it without jQuery
try this
<p><input type="text" class = "class-1" onclick="this.value='';" value="Enter Choice # 1"/></p>
To do it inline like that, you need to keep the this.value='' as part of the string:
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="this.value=\'\'" value="Enter Choice #' + i + '"/></p>');
Notice the " onclick="this.value=\'\'", where the single quotes are escaped to keep the main string from being terminated.
Here's a working example for you.
var i = 0;
$('<input type="text" class="class-'+ ++i +'" value="Enter Choice #' + i + '"/>')
.click(function(){
this.value = '';
})
.wrap('<p />')
.parent()
.appendTo('#container');
http://jsfiddle.net/jruddell/FVqjQ/