How do I set a default value in dynamically populated dropdown? Here is my code:
function loadCountryModal(countryId) {
$.ajax({
type: "GET",
url: "index.php?task=Admin.getCountryById",
data: "countryId=" + countryId,
success: function (jsonData) {
var obj = $.parseJSON(jsonData);
$("#country").val(obj['data'][0]['name']);
$.each(obj['data']['regionList'], function () {
$('#region').append(
$("<option></option>").text(this.name).val(this.region_id));
});
}
});
}
After your $.each loop, add:
$('#region').val('default_option_value');
just use .attr("selected",true);
$("#country").val(obj['data'][0]['name']).attr("selected",true);
$('#region').val('valueToSelect');
Sorry guys, I've forgot to mention ... I'm using Bootstrap's "select2-me" class to skin the dropdown
So different selector method is needed. This is the fix:
$('select').select2();
Thank you
Related
I want to append textboxValue to the URL - test.php
The URL should be test.php?variable="textboxValue"
var textboxValue = document.getElementById("textbox").value;
window.onload = function() {
window.addEventListener('shake', shakeEventDidOccur, false);
//define a custom method to fire when shake occurs.
function shakeEventDidOccur () {
$.ajax({url:"test.php?value=var textboxValue"});
}
How do I do this?
Pretty sure you can make use of the data property for this kind of thing...
$.ajax({
url: "test.php",
data: { value: textboxValue }
});
$.ajax({url:"test.php?value="+textboxValue});
OR
$.ajax(
{url:"test.php"},
{data:{value:textboxValue}}
);
You can simply concatenate.
url:"test.php?value="+$('#id').value()}
If you will use $.ajax you need to have included the jQuery source, and then you can also use the jQuery functions to do that.
Try this:
//Into your html "head" tag you need to have this:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
//And then in your code you could have something like this:
$(document).ready(function () {
window.addEventListener('shake', shakeEventDidOccur, false); //You have now the task to find what jQuery function or method could be replacing this to make your code integrated completly
//define a custom method to fire when shake occurs.
function shakeEventDidOccur () {
var textboxValue = $('#textbox').val(); //Where textbox is the "id" attr of your textbox
$.ajax({url:"test.php"
type: 'GET', //can be POST too
url: '/wp-admin/admin-ajax.php',
data: { 'value': textboxValue},
success: function (request_data) {
//some code to execute after the call as a callback
}
});
}
});
I am using an Ajax function for show the auto suggestions for search field. But, I've to search field on the same page. So, when I am trying to use this then one is work and another one isn't. It's because Both of those are using couple of same ID and Class. I style them with CSS for different width and height.
Can anyone please help me know how may I add one more ID and Class on the below code for each field?
$(document).ready(function() {
$("#email").keyup(function() {
var searchid = $(this).val();
var dataString = 'type=' + searchid;
if (searchid != ' ') {
$.ajax({
type: "POST",
url: "type_process.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show();
}
});
}
return false;
});
$(document).click(function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("get_types")) {
jQuery("#result").fadeOut();
}
});
$('#email').click(function(){
jQuery("#result").fadeIn();
});
});
When you select 2 element (or more) you can refer to a single one by specifing the element index.
$('.item').eq(0); // return the first element in a collection with class '.item'
or
$('.item').eq(1); // return second element in a collection with class '.item'
BTW, you should avoid having elements with the same ID in the DOM
If you want to select lots of differents elements, use a Class tag instead.
Mark all your elements with the same class, like: class="mySelectorClass" and then, use a jquery selector:
$(".mySelectorClass").each(function(index,value){
// ... your code for each element goes here!
});
https://api.jquery.com/jQuery.each/
I have multiple anchor tag generated by php from database like this
Now I got JQuery script
$(document).ready(function(){
$("#reply_doc").click(function () {
var a = $(this).data("doc_value");
if (a != "") {
$.ajax({
type: "POST",
url: "ajax_check/",
data: "doc_reply=" + a,
success: function (b) {
alert(a+' ok. '+b)
}
});
}
});
});
This is only applying for the first anchor tag.
How can I do this for each anchor tag when that particular is clicked only that anchor will be affected and that particular value will be send with ajax.
Any help will be appreciated. thanks in advance.
The id attribute is an identifier. As the name might suggest, that means it has to be unique so that it can identify a single element. In order to recognise multiple elements, you'll need to use a class instead:
$(".reply_doc").click(...);
Change the id to a class, and change your selector to ".reply_doc".
Your html is currently invalid because the id attribute should be unique. Although the browser doesn't jump up and down complaining when you break this rule, when you try to select an element by id it only finds the first (or, in some browsers, the last).
If, hypothetically, you have no control over the html structure you could instead select all anchor elements with the data-doc_value attribute:
$("a[data-doc_value]")...
Elements cannot have same id so bind event on same class .
a href="#" class="option" id="reply_doc" data-doc_value="1"></a>
JQuery script
$(document).ready(function(){
$(".option").click(function () {
var a = $(this).data("doc_value");
if (a != "") {
$.ajax({
type: "POST",
url: "ajax_check/",
data: "doc_reply=" + a,
success: function (b) {
alert(a+' ok. '+b)
}
});
}
});
});
Edited again DEMO
111<br>
222<br>
333<br>
$(document).ready(function(){
$(".reply_doc").click(function () {
var a = $("a.reply_doc").attr("data-doc_value"); //<-- Add this
if (a != "") {
$.ajax({
type: "POST",
url: "ajax_check/",
data: "doc_reply=" + a,
success: function (b) {
alert(a+' ok. '+b)
}
});
}
});
});
This way each time "a" will have unique value contained in data-doc_value on click
I am generating options for my dropdown by jQuery ajax method, filling it by db.
$.ajax({
type: "POST",
url: pageUrl + '/FillAssignee',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (var i = 0; i < response.d.length; i++) {
$('#SelectAssignee').append($("<option></option>").val(response.d[i]['Value']).html(response.d[i]['Text']));
}
if (response.d.length > 0)
{
$('#SelectAssignee>option:eq(1)').attr('selected', true);
alert($('#SelectAssignee').val()); //this line giving me correct value but value not showing in dropdown as selected in ie
}
}
});
It's works fine. only problem is that first value not got selected by default on IE. So for that I used many options
1. $('#SelectAssignee').val();
2. $('#SelectAssignee option:first').attr('selected','selected');
3. $('#SelectAssignee option:first').prop('selected',true);
How can I get it work?
try something like this
var selObj = document.getElementById('SelectAssignee');
selObj.selectedIndex = 0;
Your logic is saying that you are targeting the FIRST element in your select menu, however, you are adding the new option to the END of the select input. You either need to change your .append to .prepend, or target the last option when setting the selected attribute to true
Try setting as attributes rather than properties.
$('#SelectAssignee').append($("<option />", { value: response.d[i]['Value'], html: response.d[i]['Text'] }));
Could you please try below solution.
After the for loop, just add this
if (response.d.length > 0) {
$('#SelectAssignee>option:eq(1)').attr('selected', true);
}
My best guess is that this should work. Although, this seems like a dirty hack, there was an occasion when I had to resort to this and it worked.
setTimeout( function() {
$('#SelectAssignee option:first').prop('selected', true);
$('#SelectAssignee').trigger('change');
}, 1000 );
Try putting this code block in the success callback, after the for loop.
After the for loop, try following condition
if (response.d.length > 0) { $('#SelectAssignee>option:eq(0)').attr('selected', 'selected');}
Try setting the value explicitly to the value of the first option
$('#SelectAssignee').val(response.d[0]['Value']);
I'm using bsmSelect jQuery plugin. Basically, what it does is changing the way a select-multiple is rendered to make easier to pick up the options. It hides the select element and shows a list instead.
So, first of all I'm applying the plugin function to my select-multiple element:
$(document).ready(function() {
...
$('#my_select_multiple').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
...
});
On the other way, I have another select element (this one is simple) which has an ajax request bind to its change event. This ajax request get new #my_select_multiple options depending on the select simple value. Ajax response is the new HTML for #my_select_multiple options. So I have:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/
}).responseText;
return r;
}
...
$(document).ready(function() {
...
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val()));
}
...
});
AJAX is working as expected. New options are got correctly and they are inserted into #my_select_multiple (which is hidden by bsmSelect plugin, but I can check it with Firebug). But bsmSelect didn't realize new changes and doesn't get updated.
So, I think what I want is to reapply $('#my_select_multiple').bsmSelect(); with its new options.
I've been looking around a little bit and here is what I have tried.
1. I've tried to call again the funcion with the success and complete (one at time) of the AJAX request. Didn't work:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function() { $('#my_select_multiple').bsmSelect(); }
}).responseText;
return r;
}
2. I've tried to bind the function with the on jQuery function. Didn't work:
$('#my_select_simple').on('change', function() {
$('#my_select_multiple').bsmSelect();
});
3. I've tried 1 and 2 removing previosly the HTML generated by bsmSelect. Didn't work.
Thank you very much.
UPDATE: The exact code
First I have a global.js file which apply bsmSelect plugin to some select multiples (.quizzes):
$('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
And then, in the php file I define the updateQuizzes function and bind it to the select simple (project_id) change event:
<script type="text/javascript">
function updateQuizzes(project_id) {
var r = $.ajax({
type: 'GET',
url: '<?php echo url_for('event/updateQuizzes')?>'+'<?php echo ($form->getObject()->isNew()?'':'?id='.$form->getObject()->getId()).($form->getObject()->isNew()?'?project_id=':'&project_id=')?>'+project_id,
success: function() { $('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
}); }
}).responseText;
return r;
}
$('#project_id').change(function(){
$('.quizzes').html(updateQuizzes($(this).val()));
});
</script>
As I told, the AJAX request works without problems, but not the calling bsmSelect the second time...
Not sure if this is what the problem is, but you could try
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val())).trigger('change');
}
This triggers a change event on select_multiple, and might fire bsmSelect. I'm not sure what the problem here is exactly, but that's the best I can come up with.
I think you want to set your HTML in the success of the Ajax call, something like:
function loadNewOptions(val) {
$.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).bsmSelect();
}
});
}
And then calling like:
$('#my_select_simple').change() {
loadNewOptions($(this).val());
}
$(document).ready(function() {
$('#my_select_simple').change() {
$('#my_select_multiple').load("your Url", function(){
$('#my_select_multiple').bsmSelect();
});
}
});
something like this should work.
.load will put whatever your url returns into #my_select_multiple
the first parameter is the url to load, and the 2nd is a function to call when it is done. which is where you need to set up your fancy selector.
Ok, I opened a ticket and bsmSelect developer has answered me in minutes. Great!
To let bsmSelect know about its select changes, you have to trigger a change event on the select. There is no need to call bsmSelect again.
So it can be that way:
function loadNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).trigger('change');
}
}).responseText;
return r;
}
$('#my_select_simple').change(function() {
loadNewOptions($(this).val());
});