I am using the multiselect jQuery plugin in my ci app
<div class="controls"><select name="delivery_method_' + cloneCntr + '[]" multiple="multiple" class="dm_list_data">' + delivery_method_options + '</select></div>';
$(function () {
$('.dm_list_data').multiselect({
includeSelectAllOption: true,
buttonWidth: '170px',
nonSelectedText: 'Select Delivery Method',
});
});
I have created a function on change. In the function I am not getting unchecked values, it's showing only checked values:
$('.dm_list_data').on('change', function() {
var ischecked= $(this).is(':checked');
if(!ischecked){
alert('uncheckd ' + $(this).val());
} else {
alert("checked");
}
});
Hope this will help you :
see the working example : https://jsfiddle.net/3b4dqhfc/5/
Use jquery's not to get the desired result like this
$(document).ready(function(){
$('.dm_list_data').on('change', function() {
/* use this for unselected value*/
$('.dm_list_data option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
/* use this for selected value*/
$('.dm_list_data :selected').each(function(k,v){
console.log(k,v.text, v.value);
});
});
});
On every change setup some attribute to unselected and add them in the array.
$('.dm_list_data').on('change', function() {
var $sel = $(this);
val = $(this).val();
$opts = $sel.children();
prevUnselected = $sel.data('unselected');
var currUnselected = $opts.not(':selected').map(function() {
if($("#new-input-"+this.value).length > 0){
$("#new-input-"+this.value).remove();
}
return this.value
}).get();
var currSelected = $('.dm_list_data').val();
$.each(currSelected, function(index, item) {
if($("#new-input-"+item).length == 0){
$("#new-options").append("<input type='text' id='new-input-"+item+"' value='"+item+"'>");
}
});
});
Updated as needed
Add one new div <div id="new-options"></div>
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
In my AJAX success function, I've written:
rt = JSON.parse(responseText);
for (i = 0; i < rt.length; i++) {
$("#inv").append("<tr><td>" + rt[i][0] +
"</td><td><input type='submit' value='Sync' " +
"class='syncnow' id='sync"+rt[i][6]+"' /></td></tr>");
}
I've tried jQuery code:
$(".syncnow").on("click", function() {
alert("Hi");
});
Tried .click(), $(".tdclass").on("click", ".syncnow", function() {}) etc., but to no avail. Can anyone help me with this?
You can't add an event to a not yet created element. You need to add it to a higher place and catch it when it is bubbling up.
Try this:
$("body").on("click", ".syncnow", function() {
console.log('clicked');
} )
$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
You can attach event to element when created using jQuery()
$.each(rt, function(i, value) {
$("<tr>", {
appendTo: "#inv",
html: $("<td>", {
html: value[0],
append: $("<input>", {
type: "submit",
value: "Sync",
"class": "syncnow",
id: value[6],
on: {
click: function(event) {
console.log("clicked");
}
}
})
})
})
})
Try this one
$(document).on("click", ".syncnow", function() {
alert('clicked');
} )
$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
I've written a jquery function, to append syncbuttons to an invElement
$.fn.appendSyncElements = function(responseText, onComplete) {
var invElement = $(this);
var rt = JSON.parse(responseText);
var base_sync_attrs = [];
base_sync_attrs.push("type=\"submit\"");
base_sync_attrs.push("value=\"Sync\"");
base_sync_attrs.push("class=\"syncnow\"");
var base_sync_attrs_str = base_sync_attrs.join(' ');
for(var i = 0; i < rt.length; i++) {
var crt = rt[i];
var crt_sync_label = crt[0];
var crt_sync_attrs = crt[6];
var sync_attrs = [];
sync_attrs.push(base_sync_attrs_str);
sync_attrs.push("id=\"sync_" + String(i) + "\"");
sync_attrs.push("data-sync_index=\"" + String(i) + "\"");
sync_attrs.push(crt_sync_attrs);
var sync_attrs_str = sync_attrs.join(' ');
var syncElement = $('<input ' + sync_attrs_str + ' />');
syncElement.click(function(e) {
var syncBtn = $(this);
console.log("the syncBtn was clicked at index " + String(syncBtn.data('sync_index'));
var syncEvent = {
'event' : e,
'button' : syncBtn,
'fullresponse': crt,
};
if(typeof(onComplete) === 'function') {
onComplete(syncEvent)
};
});
var tableRowElement = $('<tr><td class="synclabel" ></td><td class="syncinput" ></td></tr>');
tableRowElement.find("td.synclabel").html(crt_sync_label);
tableRowElement.find("td.syncinput").append(syncElement);
invElement.append(tableRowElement);
};
};
Usage
$("#inv").appendSyncElements(responseText);
Or
$("#inv").appendSyncElements(responseText, function(syncResult) {
console.log("This is a custom Complete Method");
});
You can use document on click event:
$(document).on("click",".syncnow",function() {
alert("Working");
});
Also you can check my answer here:
Why is jQuery on-click event handler not working properly for dynamic loaded DOM elements?
Thanks
$("body").on("click",".syncnow", function() {} )
I know some php/html/css but javascript is where I need help. I found on web autocomplete script, but this doesn't work on more than two input fields.
There are two problems I need to solve.
When you type in first box, autocomplete shows in second one. How to make script show autocomplete on box where user is typing?
I need to use the same autocomplete on multiple fields on my site.
The javascript syntax I use is:
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "http://example.com/autofill/auto-complete.php", { keyword: keyword } )
.done(function( data ) {
$('#results').html('');
var results = jQuery.parseJSON(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">' + value + '</div>');
})
$('.item').click(function() {
var text = $(this).html();
$('#keyword').val(text);
})
});
} else {
$('#results').html('');
}
});
$("#keyword").blur(function(){
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});
});
In order to re-use the same autocomplete code you need to give the scope of the function the context of the correct DOM element.
Here's a a quick jsfiddle with some simple HTML code, but it should give a basic example of how to bind the same events to multiple dom structures.
DEMO: JSfiddle example
JS
var MIN_LENGTH = 2;
$(document).ready(function() {
$(".keyword").keyup(function() {
var $parent = $(this).parent();
var $results = $parent.find('.results');
var keyword = $(this).val();
if (keyword.length >= MIN_LENGTH) {
$.get("/echo/json/", {
keyword: keyword
})
.done(function(data) {
$results.html('');
data = ['test', 'test2'];
//data = jQuery.parseJSON(data);
$(data).each(function(key, value) {
$results.append('<div class="item">' + value + '</div>');
});
});
} else {
$results.html('');
}
});
});
HTML
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
I want help on how to append the value of textbox1 to textbox2 when the value of textbox1 changes
$(function () {
$('#textbox1').on('change', function () {
$text1 = $('#textbox1');
$text2 = $('#textbox2');
$text2.val($text2.val() + ' $text1');
});
});
You should be $text1.val() just as you are with $text2.
$(function () {
$('#textbox1').on('change', function () {
$text1 = $('#textbox1');
$text2 = $('#textbox2');
$text2.val($text2.val() + $text1.val());
});
});
I'm in the middle of a problem here.
I have a Ajax script that returns this "Rua Américo Vezzani#Park Aliança#Matão#SP", then I split this result and match with the options of a select tag
function (retorno)
{
var array_retorno = retorno.split('#');
$(".endereco_load").val(array_retorno[0]);
$(".bairro_load").val(array_retorno[1]);
$(".cidade_load").val(array_retorno[2]);
var estado = array_retorno[3].toString() ;
$(".estado_load ").find('option').each(function() {
if( $(this).val().match(estado) ) {
$(this).attr({ selected : "selected" });
}
});
// $(".estado_load option[value='" + estado + "']").attr({ selected : "selected" });
},
the problem is that the code above doesnt work.
when i set my variable estado like this for instance
var estado = 'SP';
it works
can anyone help me?
You didn't name your function and .toString isn't necessary.
See Fiddle: http://jsfiddle.net/13s58xjj/
function splitString(retorno)
{
var array_retorno = retorno.split('#');
$(".endereco_load").val(array_retorno[0]);
$(".bairro_load").val(array_retorno[1]);
$(".cidade_load").val(array_retorno[2]);
var estado = array_retorno[3];
alert(estado);
$(".estado_load ").find('option').each(function() {
if( $(this).val().match(estado) ) {
$(this).attr({ selected : "selected" });
}
});
You can remove the alert, I left it in for debugging
Change:
$(".estado_load ").find('option').each(function() {
if( $(this).val().match(estado) ) {
$(this).attr({ selected : "selected" });
}
});
To:
$(".estado_load option").filter(function() {
return this.value.trim() == estado.trim();
})
.attr('selected','selected');
You should try to trim like this:
if( $(this).val().trim().match(estado.trim())) {
// all stuff here
}
Working Fiddle.
I have a list of checkboxes. Upon clicking on each of the checkboxes i am adding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the checkbox . How this piece cab be done
here is the hidden form variable
<input name="IDList[]" type="hidden" id="IDList" value="" />
and the jquery
$(".myCheckboxClass").change(function() {
var output = 0;
$(".myCheckboxClass").change(function() {
if ($(this).is(":checked")) {
output += ", " + $(this).val();
} else {
output = $.grep(output, function(value) {
return value != $(this).val();
});
}
$("#IDList").val(output);
});
});
Something like this: (demo) http://jsfiddle.net/wesbos/5N2kb/1/
we use an object called vals to store the info. ADding and removing as we check/uncheck.
var vals = {};
$('input[type=checkbox]').click(function() {
var that = $(this);
if (that.is(':checked')) {
console.log(this.name);
vals[this.name] = "In your Object";
}
else {
delete vals[this.name];
}
console.log(vals);
});
Following your logic, you could do this:
$('#IDList').data('value', []);
$(".myCheckboxClass").change(function() {
var list = $('#IDList').data('value');
if ($(this).is(":checked")) {
list.push($(this).val());
} else {
var indexToRemove = list.indexOf($(this).val());
list.splice(indexToRemove, 1);
}
$('#IDList').val(list);
});
But if you only care about the value of #IDList upon data submission or other actions, you probably want to consider an alternative approach: collating the checked values when you need them.
$('#form').submit(function() {
var list = $('input.myCheckboxClass:checked', this).map(function() {
return $(this).val();
}).get();
$('#IDList').val(list);
});
See both of the above in action: http://jsfiddle.net/william/F6gVg/1/.