I have severall select2 in my page.
I have a specific ajax engine and can't change it for many reasons.
i would like to fill each select2 dropdown when the end-user type in the field, and use home made javascript to fill the "options" in the select2.
I've tried many different things found on the net, and can't find a working syntax for that.
For instance :
jQuery("customer").select2({
query: function (options) {
alert('ok');
// my ajax call would be here
xajax_getCustomers(stringFilled);
}
});
i've tried with "ajax:" and several other things, i can't find how to trigger a javascript function when something filled.
Important : i should be able to get the string filled, in order to pass it to my ajax call
Thanks for your help
You have got this event:
$(selector).on("select2-highlight", function(e) {
console.log("highlighted val=" + e.val + " choice=" + e.choice.text);
})
It's valid for a search event, so when select2-highlight event is fired means that user is searching for a string that you can manage with the e.val and e.choice.text values.
Unfortunatelly there's no strict search event, but you can bind the hided input text of the plugin with a on('keyup');
Something like this:
$('input.select2-search__field').on('keyup', function() {
alert($(this).val()); // it alerts with the string that the user is searching
});
Related
If I have a validation tag in my asp.net mvc application for a text field called search, can I plug into it using jquery/javascript to get it to trigger if certain logic is performed? How would I do that?
It looks something like this
#Html.TextBox("SearchQuery", other stuff here, other)
#Html.ValidationMessageFor("SearchQuery")
Say I want to trigger the validation message to show if this occurs
$('form').submit( function (e) {
e.preventDefault(e);
var results = GetLocation();
if (results) {
this.submit();
} else {
// trigger validation message and display "can't find results"
}
});
Please note that I don't think I need to validate here, I just want to show a message where the validation message would be if I did validate
As far as i understand your question, for custom messages coming from server you need to send the object to server and then get the response from it.
You can perform it with an ajax call for example:
$.ajax({
url : 'example.com',
type: 'POST',
data : results,
success:function(datafromserver)
{
$('.resultState').html(datafromserver);
}
});
Another thing if do validation first in the client and then send (and check again in server), in this case remember var result can always be true if the getLocation functions returns anything (such as string , object etc...) so in this case print it with console.log and take a look if is it an object (f example: data.x === none or 'no coordinates' just evaluate it correctly and you can avoid ajax.
Hope helped!
Regards
Below is a function which is called in my alpaca "postRender" callback :
function onClickDefaultParameterButtons(renderedForm) {
$('#paramFormSaveBtn')
.click(
function() {
if (renderedForm.isValid(true)) {
val = renderedForm.getValue();
paramIdDefaultMap[curParameterIdSelect].Parameter.Value = JSON
.stringify(val);
genericJsonAjaxCall(
"${RestUrlBase}/DefaultParameters/"
+ curParameterIdSelect,
"put",
JSON.stringify(paramIdDefaultMap[curParameterIdSelect]),
saveDefaultParameterChangesSuccessCallback,
false);
}
});
}
I have a checkbox in this form and it has some issues with serialization.
For example, if the checkbox is checked, it will show up as a value in the renderedForm.getValue() return.
If the checkbox is not checked, it will not show up as a value in the renderedForm.getValue() return.
Another issue I found is when I have a number field and put the value of 0, it also does not show up in the renderedForm.getValue(). I need all form values to show up whether they are checked, not checked or even 0.
Is there a way to get around this?
Others have said that POST/GET behaviour of the browser is to blame, but that's not the case for raw JSON serialization. You should be able to serialize your data and POST the raw JSON result to some service without a problem. The way a browser encodes form elements is not relevant to that.
The problem is in the alpaca's serialization code itself, where fields are only added if their value would pass this statement:
if (assignedValue)
{
o[propertyId] = assignedValue;
}
So, if assignedValue is 0, or false, it won't be serialized. This is different than expected behaviour, which I think makes it a bug.
I have forked the alpaca code to handle this serialization as you (and I) would expect. A pull request is pending. Feel free to use it as is:
https://github.com/tylerperyea/alpaca
Or just change this contents of the js/fields/basic/ObjectField.js file, and rebuild.
You may also comment on the issue:
https://github.com/gitana/alpaca/issues/158
I have a modal window that has a lot of new dynamic elements (inputs, buttons, etc.). I want to see if a certain element(or in this case, and input) gets created and if it does, then change its value.
The scenario is that if I make an ajax request for populating data, and as the user browses the modal window I can reuse some of that data. When the input field I'm looking for gets created, I can just put the value of the ajax call I made previously.
I have tried: $("#myinput_id").val(sellerData['id']);
obviously the above wont work because the element doesn't exists, yet. I'm also trying to avoid new ajax calls for the same data :/
Any thoughts?
$( "#add").bind('click', function() {
$.ajax({
url: '/seller/get',
type: 'POST',
success: function(response) {
sellerData = jQuery.parseJSON(response);
//other code here
//this doesn't work
$("#myinput_id").val(sellerData['id']);
}
});
});
Then the above gets triggers. The input field doesn't exist yet. How can I make it "look for it" if in the future the input field gets created?
Try using .length http://api.jquery.com/length/
if($("#myinput_id").length) //There is at least one element selected
//Do something
a bit confusing question you are saying u want to populate the data and your are using POST
Im running into a problem where i have an ajax driven page that is drawn when a user selects something from a simple drop down:
<select id = "selectdepartment">
<option id = "default">Select an option...</option>
....
</select>
and the remainder of the page is drawn using the jquery .change() :
$('#selectdepartment').change(function(){
});
Which then runs some ajax to php script. everything works great, the problem is when i submit a form that was drawn with ajax (using $_SERVER['PHP_SELF'];), the data gets submited, the page reloads, and the page is cleared but the select box is still left where it was. The user has to move to a different option then back to the one the selected originally to re-fire the .change(). that sucks.
I could fix this by passing a php variable in all of my forms, then checking to see the variable set on every page load and if it is draw the page parts then, but this would lead to pretty messy code and it's less than desirable.
There has to be a way to do this with the jquery library, though my knowledge of the javascript language in general is not what i would like it to be. If anyone has any helpful hints please share, dont do it for me though, i wont learn that way :)
edit: code with .trigger
$('#selectdepartment').change(function(){
var department = $('#selectdepartment').val();
var day = $('#data').data('day');
var month = $('#data').data('month');
var year = $('#data').data('year');
//alert (department);
if(department === "Select an option..."){
$('.hiddenuntildepartmentisselected').css({"display":"none"});
}
else{
$('.hiddenuntildepartmentisselected').css({"display":"block"});
}
showpoints(department);
drawpointstable(department, day, month, year);
displaytheuseresforselecteddepartment(department, '');
$('#sendthedepartment').val(''+department+'');
$('#hiddendepartmentidforaddinganewpoint').val(''+department+'');
}).trigger('change');//end run functions
You can use the .trigger() function to immediately trigger the change event handler when the page has loaded:
$('#selectdepartment').change(function() {
// code here
}).trigger('change');
Or if you need to call it elsewhere via JavaScript/jQuery:
$('#selectdepartment').trigger('change'); // or just .change() as a shorthand
Updated
Your button for the form could make use of the onClick attribute, which would invoke a method to parse the form fields and post the data to your php script via .ajax().
In the success event method you then check any flags you need to and modify the element as you desire if needed.
Basic example:
Inside of .ajax():
...
url: 'xxx.xxx.xxx',
async: true,
type: 'POST',
dataType: 'html',
data: JSON.stringify( form_fields ),
beforeSend: function()
{
// Pre send stuff, like starting a loading gif
},
success: function( data, textStatus, xhr )
{
// Be sure you load the page with the content first
$( '#containing-div' ).html( data );
// Do your check here, and modify your element if needed here
if( flagtocheck === 'xxx' )
{
// Modify the element in question...
}
// I call a custom method termed `.ctrls()` here that makes any
// adjustments to the DOM once its loaded/updated.
},
error: function( xhr, textStatus, errorThrown )
{
}
Of course, you'll want to set flagtocheck appropriately in your case.
Hope that helps!
Note regarding edit
This post was edited to be a little more descriptive and more easily understood. Since the person asking the question is already using the .ajax() method, the success event method is the ideal place for doing what the person asking the question is requesting. It is 1 less method invocation to directly modify the element there than using it to call .trigger() or .change() which then also directly modifies the element.
I am using jQuery to get a list of suppliers for a part number.
I then want to load some extra data about the supplier/part number combination once the edit form appears. The problem is that the dataurl method (which I am calling in the beforeInitData method) to get the suppliers does not complete before the beforeShowForm method executes. Therefore I do not have a supplier to look up when the form first loads. Is there a way to run the function after the dataUrl method completes to get the extra data?
I have tried JQGrid editoptions dataurl not using ajax get? and got it going but I know there will be conflicts because the ajaxSelectOptions method gets called for every request and sometimes my requests will be coming from different places with different requirements.
Here is the code that I am using for my grid:
jQuery("#receiptPartsTable").jqGrid('editGridRow',"new",
{
height:400,
width:800,
reloadAfterSubmit:false,
recreateForm: true,
beforeInitData: function(form)
{
var selectedPart = rowData.part;
var selectedPartQty = rowData.qty;
//Getting list of suppliers
$("#receiptPartsTable").jqGrid('setColProp', 'supplier', { editoptions:{dataUrl:'getSuppliersForPart.php?part=' + rowData.part} });
},
beforeShowForm: function(form)
{
var selectedPart = rowData.part;
var selectedPartQty = rowData.qty;
$('#part').val(selectedPart);
$('#qty').val(selectedPartQty);
//$('#supplier').val() is not set yet;
var supplier = $('#supplier').val();
//This method is getting called before there is a supplier
getPartDetails(rowData.part, supplier);
//Set up onChange listener. After selecting a supplier, get the part details
$('#supplier').change(function() {
var supplier = $('#supplier').val();
getPartDetails(selectedPart, supplier);
});
}
You posted no definition of jqGrid which you use. The context in which you execute the above code is also not quite clear. Do you get rowData before from the currently selected row? Where you define it?
Nevertheless I think that you went in the correct direction and that you found already the correct way to solve the problem. The usage of complete callback of ajaxSelectOptions is probably the only way which you can use. You wrote about some "conflicts", but not posted more details.
I would recommend you to examine properties of this inside of complete callback. jqGrid set context option (see the line) of the $.ajax call (exactly like in the answer which you already found yourself). So you can use this.elem, this.options and this.vl inside of complete callback. this.vl is the value from the cell in case if editing of existing row. Typically it's the name of the option which will be selected. this.options has tree important properties which you can use: this.options.dataUrl, this.options.id, this.options.name. In case of form editing are the values this.options.id and this.options.name the same. In case of inline editing this.options.id will have rowid and _ ad the prefix. It gives you the possibility to execute different code inside of complete callback for different selects where you use dataUrl.
One more remark. In the most cases you can remove call of setColProp from the beforeInitData and use the approach suggested in the answer and the another one:
ajaxSelectOptions: {
data: {
id: function () {
return $("#receiptPartsTable").getGridParam('selrow');
},
part: function () {
return rowData.part;
}
},
complete: function (jqXHR, textStatus) {
var columName = this.options.name, response = jqXHR.responseText;
...
}
}
You can use just editoptions: {dataUrl: "getSuppliersForPart.php"} The URL will be appended with part and id parameters (see the above code). Instead of id you could use getRowData to get content from other columns based of rowid of currently selected row for example.