How to send multiple values from a checkbox input - javascript

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

Related

Jquery Autocomplete not working correctly

I'm using jquery autocomplete.In my case I have multiple autocomplete textbox and hidden field on my page.
e.g
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
and so on...
so when I fire change event on hidden field then it is raised multiple time
below is my code:
$(".myclass").each(function() {
var $empName= $(this);
var $empNumber = $empName.next('input:hidden');
//things to do
//Setting variable e.g url...
$empName.autocomplete(url,{
//code...
}).result(function(event,data,formatted)
{
$empNumber.val(formatted).change();
});
});
In above code $empNumber holds the hidden field which is used to store autocomplete value i.e in this case when
we select any text from autocomplete then that selected employees number will get store in hidden field.
Based on this hidden field value I want to do ajax call which will return full details of the employee based on his
employee number.
So I have written hanldler to change event of the hidden field as below.
$(.emp_num_hidden).on('change',function (
)};
here 'emp_num_hidden' is the class of the hidden field.
Please suggest how can I prevent multiple event on hidden field change.
This is done using the $(this) object. Since the change event has a target, it will only be effecting one element. The callback function is being executed on this element, this. For example:
$(".emp_num_hidden").on('change', function (e){
alert($(this).val());
});
What will happen is that an alert window will be shown when the hidden field is changed, containing the employee number from only that hidden field. You will also notices there are a few fixes to your code.
Personally, I would make use of both id and class attributes on your objects. This gives you wide scope and narrow scope to your selectors.
Example:
HTML
<input class='myclass' type='text' id='entry-txt-1' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-1' />
<input class='myclass' type='text' id='entry-txt-2' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-2' />
jQuery
$(function(){
var $empName, $empNumber;
$(".myclass").each(function(key, el) {
$empName= $(el);
$empNumber = $empName.next("input[type='hidden']");
// things to do
// Setting variable e.g url...
$empName.autocomplete(url, {
//code...
}).result(function(e, d, f){
$empNumber.val(f).change();
});
});
$(".emp_num_hidden").on('change', function(e){
var empId = $(this).attr("id");
var $employeeNumberField = $("#" + empId);
// Do the needful...
});
});
Taking this a bit further, you may want to consider making use of data attributes. You may also want to look at select event for Autocomplete. Something like:
$(function(){
$(".myclass").autocomplete({
source: url,
select: function(e, ui){
$(this).val(ui.item.label);
$(this).data("emp-number", ui.item.value);
$.post("employeedata.php", { n: ui.item.value }, function(data){
$("#empData").html(data);
});
return false;
}
});
});
This assumes that url returns an array objects with label and value properties. This would add the Employee Number as a data-emp-number attribute to the field that the user was making a selection from. The label being their Employee Name, and the value being their Employee Number. You could also use this callback to show all the other employee data based on Employee Number.
A working example: https://jsfiddle.net/Twisty/zmevd0r0/

Jquery multiple plus/minus script

I have multiple forms on a page and also multiple input boxes with plus/minus signs.
I'm having trouble to get those input boxes to work seperately. Probably because of some wrong/same id's or something like that or maybe a wrong setup of my code. The thing is I can't find my error in the code and I don't get any errors in my console.
What I have:
function quantity_change(way, id){
quantity = $('#product_amount_'+id).val();
if(way=='up'){
quantity++;
} else {
quantity--;
}
if(quantity<1){
quantity = 1;
}
if(quantity>10){
quantity = 10;
}
$('#product_amount_'+id).val(quantity);
}
And my html:
//row 1
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_1234"/></div>
<div class="change" data-id="1234">
+
-
</div>
//row 2
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_4321"/></div>
<div class="change" data-id="4321">
+
-
</div>
I thought something like this would do the trick but it doesn't :(
$(document).ready(function(){
$('.change a').click(function(){
var id = $(this).find('.change').data('id');
quantity_change(id)
});
});
Any help greatly appreciated!
You should use closest() method to get access to the parent div with class change, then you can read the data attribute id's value.
var id = $(this).closest('.change').data('id');
alert(id);
Since you are already binding the click event using unobutrusive javascript, you do not need the onclick code in your HTML markup.
Also your quantity_change method takes 2 parameters and using both, but you are passing only one. You may keep the value of way in HTML 5 data attributes on the anchor tag and read from that and pass that to your method.
<div class="change" data-id="1234">
+
-
</div>
So the corrected js code is
$(document).ready(function(){
$('.change a').click(function(e){
e.preventDefault();
var _this=$(this);
var id = _this.closest('.change').data('id');
var way= _this.data("way");
quantity_change(way,id)
});
});
Here is a working sample.

Deleted specific appended element with jquery

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);
}());

onclick checkbox append checkbox value to URL

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/

Persisting textbox value using jQuery

I'd like to save the newly entered values, so I could reuse them. However, when I try to do the following, it does not work:
// el is a textbox on which .change() was triggered
$(el).attr("value", $(el).val());
When the line executes, no errors are generated, yet Firebug doesn't show that the value attribute of el has changed. I tried the following as well, but no luck:
$(el).val($(el).val());
The reason I'm trying to do this is to preserve the values in the text boxes when I append new content to a container using jTemplates. The old content is saved in a variable and then prepended to the container. However, all the values that were entered into the text boxes get lost
var des_cntr = $("#pnlDesignations");
old = des_cntr.html();
des_cntr.setTemplate( $("#tplDesignations").html() );
des_cntr.processTemplate({
Code: code,
Value: val,
DivisionCode: div,
Amount: 0.00
});
des_cntr.prepend(old);
This is the template:
<div id="pnlDesignations">
<script type="text/html" id="tplDesignations">
<div>
<label>{$T.Value} $</label>
<input type="text" value="{$T.Amount}" />
<button>Remove</button>
<input type="hidden" name="code" value="{$T.Code}" />
<input type="hidden" name="div" value="{$T.DivisionCode}" />
</div>
</script>
</div>
You want to save the previous value and use in the next change event?
This example uses .data to save the previous value. See on jsFiddle.
$("input").change(function(){
var $this = $(this);
var prev = $this.data("prev"); // first time is undefined
alert("Prev: " + prev + "\nNow: " + $this.val());
$this.data("prev", $this.val()); // save current value
});
jQuery .data
If you want old/Initial text box value, you can use single line code as follows.
var current_amount_initial_value = $("#form_id").find("input[type='text']id*='current_amount']").prop("defaultValue");
If you want current value in the text box, you can use following code
$("#form_id").find("input[type='text']id*='current_amount']").val();

Categories