Select2 onchange not working - javascript

When I've added select2 to all selects in my app it worked very nice except when in my select is this property(it works when I don't use select2):
onchange="'refresh()'"
Function refresh:
function refresh()
{
document.forms[0].submit();
}
This is how I run select2
$("select").each(function(){
var this1 = $(this);
if(this1.attr('multiple')!='multiple')
{
this1.select2();
}
});
How to pass this? Or maybe there is some mechanism inside the select2 that deals with that kind of problems? All kinds of suggestions are welcome:D

you need to update this:
$(#Select/Input Element).select2();
$("#select/input element").change(function () {
var valueToSet = $("#select/input element").select2('data').text;
$('#hiddent field to which data to be set').val(valueToSet);
});

Not sure to understand. When one of yours selects changes, you want to call the refresh method? In that case :
$("select").each(function(){
var $this = $(this);
if($this.attr('multiple')!='multiple'){
$this.select2();
$this.change(refresh);
}
});

Remove single quote from onchange="'refresh()'. Try as mentioned below :
<input type="checkbox" onchange="Refresh();"/>
And your script will be defined as below :
<script type="text/javascript">
function Refresh() {
alert('refresh');
}
</script>

Related

I get 'Bad assignment' when trying to use $(this) inside function after .load() method

I couldn't find any solutions for my problem yet. Maybe I used wrong keywords.
I'm trying to update the value of an input field onchange after a .load() action has been performed.
Here is my script:
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(this).val('OK');
});
});
So, after someAction.php has been loaded into #actionDiv successfully, I'd like to change the value of that input field, that has been changed.
I have several input fileds, which take this kind of action...
It seems "$(this)" is unknown in the function after load() has been completed.
Can anyone please help?
Thanks
You need to store a reference to the element, or use an arrow method which doesn't change the value of this
$(document).on("change",".myInput",function() {
var that = this;
var value = $(that).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(that).val('OK');
});
});
OR
$(document).on("change",".myInput",function(e) {
var value = $(e.target).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(e.target).val('OK');
});
});
OR
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, () =>{
$(this).val('OK');
});
});

jquery - Copy one row of table to another

I have this portion of code:
$('input[type=checkbox]').change(function() {
if(this.checked) {
var row = $(this).closest('tr').html();
$('#two').append('<tr>'+row+'</tr>');
}
});
function clearSel(){
$('input[type=checkbox]').each(function() {
this.checked = false;
});
$("#two").empty();
}
This code works fine on a local folder. When I put it on a web app on xampp, just the clearSel() function works. The table one content is generated from a AJAX request on a php file which return rows. In first stage of accessing the page both tables exists, but are empty. I don't understand why on xampp fails. Some suggestions? Thank you.
[EDIT] The code provided of Super User works fine. I am newbie, i didnt know anything about event delegation(i will study) . Thank you for answer!!!!
You can use event delegation here, check updated code below..
detail reference
$(document).on('change', 'input[type=checkbox]', function() {
if(this.checked) {
var row = $(this).closest('tr').html();
$('#two').append('<tr>'+row+'</tr>');
}
});
function clearSel(){
$('input[type=checkbox]').each(function() {
this.checked = false;
});
$("#two").empty();
}

Calling a function everytime user types

I have the following function, I want to get called everytime, user types something in the typeahead input field.
function getAllActiveUsers() {
var userList = $('#usersTable').jqGrid('getGridParam').userData;
var userNames = {};
if(userList) {
// Return the list of all active users
$(userList).each(function() {
if(this.userStatus != 1) {
// If the user is verified
// Could be active/inactive
userNames.user = this.username;
}
});
}
return JSON.stringify(userNames);
}
HTML:
<div id="the-basics">
<input class="typeahead" type="text" data-provide="typeahead" placeholder="User List">
</div>
I have been browsing through, the examples, but do not understand how to implement this functionality.
Edit:
Why it doesn't work when I initialize as :
$('.typeahead').typeahead({
source : getAllActiveUsers
});
Try this
$(document).ready(function(){
$('.typeahead').keyup(function(){
getAllActiveUsers();
});
});
You can use .keyup jquery function
$( ".typeahead" ).keyup(function() {
getAllActiveUsers();
});
Taken from the reference you gave you can specify the class .typeahead inside the id #the-basics:
$(document).ready(function(){
$('#the-basics .typeahead').typeahead({
//code here;
}
}
Since the page can't be manipulated safely until the document is ready you should be using $(document).ready.
Also, try to use your browser console and check if you can reach $('#the-basics .typeahead')
You can use Jquery Keyup which gets triggered when a key is released.
$( ".typeahead" ).on('keyup',function() {
getAllActiveUsers();
});
if your text box coming dynamically then you should try
$(document).on("keyup", ".typeahead" , function() {
getAllActiveUsers();
});
try this and let us know if its works or not.
It should be possible
var getAllActiveUsers = function(q, cb, cb2) {
// cb for sync, cb2 for async
var userList = $('#usersTable').jqGrid('getGridParam').userData;
var filterted = /* whatever you want to do with q */;
cb(filtered);
};
$('.typeahead').typeahead({
/* Options */
},
{
source : getAllActiveUsers
});

Jquery get value and display in span

i've got a select field with few options, each of them has assigned "value" attribute and they got names. Upon selecting one of the options, I want one to be filled with the title, second one with the value. Title works fine, but I can't get it to catch the assigned "value="asd"" value.
$(".itemclass").on("change", function () {
$("span.iclass").text(this.options[this.selectedIndex].textContent);
$("span.impl").text(this.options[this.selectedIndex].val());
});
What am I missing?
Here's how you can access the selected option:
$(".itemclass").on("change", function () {
var selectedOption = $(this).find("option:selected");
$("span.iclass").text(selectedOption.text());
$("span.impl").text(selectedOption.val());
});
Or alternatively if you prefer to use the DOM node:
$(".itemclass").on("change", function () {
var selectedOption = $(this).find("option:selected").get(0);
$("span.iclass").text(selectedOption.textContent);
$("span.impl").text(selectedOption.value);
});
Ok I did a little fiddling pardon the pun.
Here is what I came up with.
$(".itemclass").change(function()
{
$("#Name").text(this.options[this.selectedIndex].textContent);
$("#Value").text(this.options[this.selectedIndex].value);
});
Here is my fiddle
http://jsfiddle.net/nH2a3/
Here is where I found your solution Check out the answer for this question for the why.
HTMLInputElement has no method 'val'
Use this:
$(".itemclass").on("change", function () {
$("span.iclass").text(this.options[this.selectedIndex].textContent);
$("span.impl").text($(this).val());
});
You can give it a try with this code:
$(".itemclass").on("change", function () {
$("span.iclass").text($(this).find("option:selected").text());
$("span.impl").text($(this).find("option:selected").val());
});

Create Generic Javascript/Jquery ajax function

I'm new to javascript, jquery, and ajax and need help making my code more efficient. I have the following javascript/jquery function that works fine:
<script type="text/javascript">
$(document).ready(function()
{
$("#promo1").change(function() //select menu id that triggers script on change
{
//data here
$.ajax
({
//ajax stuff here
{
//individual values from json array
//set each value textbook value
$("#discprice1").val(disc);
$("#itemprice1").val(total);
$("#tax").val(tax);
$("#grandtotal").val(grand);
}
});
});
});
</script>
I change my original function to this after a suggestion:
<script type="text/javascript">
$(document).ready(function()
{
var setupCalculation = function(index) {
$("#promo" + index).on("change", function() //select menu id that triggers script on change
{
//rest of the function is here....
and change my select to this:
<select name="promo<?php echo $i; ?>" id="promo<?php echo $i; ?>"
onchange="setupCalculation('<?php echo $i; ?>');">
However, it is not working. What am I missing?
However, I need to do the same thing 10 times for 10 different rows of calculations. How can I make it so I can use this function generically and just pass the "id" of the select box to the function and not repeat this code 10 times for each of the selectors, e.g. #promo1, #promo2, #promo3, etc....
I'm assuming I need to add onchange="javascript function here();" to the html code, but I can't get it to work.
Thanks!
This is a case when you should write a little plugin. Take a look how it can look like (I did'nt get what exectly you need but you will grasp the idea):
$.fn.myFirstPlugin = functin() {
return this.each(function() {
// This is currect select box
var $select = $(this);
// Change event
$select.change(function() {
// Do something for this select box; $(this) will point to current select element
$.ajax({ ... })
});
})
};
Then you would use it like:
$('#promo1, #promo2, #promo3').myFirstPlugin();
Instead of using an "onchange" attribute inline, I would use your current approach to wireup the event handler. That way you can define a function setupCalculation that wires up the logic for a given select list.
$(document).ready(function() {
var setupCalculation = function(id) {
$("#" + id).on("change", function() {
// ajax/calculation logic
});
}
setupCalculation("promo1");
setupCalculation("promo2");
// ...etc
});
If the result elements are different (eg discprice2, discprice3, etc), then it may be better to pass an index to the function instead, and hard-code the name part of the ids:
var setupCalculation = function(index) {
$("#promo" + index).on("change", function() {
// ajax stuff
$("#discprice" + index).val(disc);
// etc
});
}
Edit Using the form onchange=setupCalculation(), the function should look like this (no need to wire up the change event):
$(document).ready(function()
{
window.setupCalculation = function(index) {
//rest of the function is here....
sounds like your select boxes look like
<select id="promo1">...</select>
<select id="promo2">...</select>
add a class to each one
<select id="promo1" class="promo">...</select>
<select id="promo2" class="promo">...</select>
so that you can select all the boxes with one simple selector for the change event function:
$(".promo").change(function() {
...
});
You could set up a jQuery function and call it from the selected object:
$.fn.changePromo = function() {
/* return this jQuery object to allow chaining and execute in an 'each()' to allow multiple elements */
return this.each( function() {
$( this ).change( function() {
/* your ajax call here */
} );
} );
}
/* call examples */
$( '#promo1' ).changePromo();
$( '#promo1,#promo2' ).changePromo();

Categories

Resources