I want to have two different Autocomplete boxes but both using the same AJAX method in the background.
Here is my script
$(document).ready(function () {
$("#SearchProject")
.each(function () {
var urlloc = "/Project/FindProjects";
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: urlloc, type: "POST", dataType: "json",
data: { searchString: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.name, value: item.name, id: item.id }
}))
}
})
},
select: function (event, ui) {
$("[id$='ProjectID']").val(ui.item.id);
// alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
// : "Nothing selected, input was " + this.value);
}
});
});
});
I want my input fields on the form as below.
<input id="SearchProject" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID" value="" />
<input id="SearchProject2" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID2" value="" />
When autocomplete select is complete I want the corresponding hidden field to be updated.
How do i achieve this?
Two possibilities:
First (the one I prefer): extract your auto-complete setup into a method:
function configureAutocomplete(autoField, updatedField)
You call this method for as many auto-complete fields as you want, passing it two JQuery selectors: the selector for the auto-complete field, and the hidden update field.
The other way is to base the ID of the hidden field on that of the auto-complete field. This will let you use an each to attach behavior to the fields, but I think it' more trouble than it's worth.
Related
I am working with select2 to display the data return from the API. However, the data didn't manage to load out.Am I doing something wrong? Any ideas how to fix this?
HTML:
<select class="js-example-basic-single form-control select2 select2-hidden-accessible" id="user" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
script:
var url = "{{env('API_URL')}}";
var username = null;
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "jsonp",
method: "GET",
data: function (term) {
username = term.term;
return {"username": username};
},
url: url+"user/search/username?",
results: function (data) {
return {
results: data.result.users
};
},
},
formatResult: function (option) {
return "<option value='" + option.id + "'>" + option.username + "</option>";
},
formatSelection: function (option) {
return option.id;
}
});
result return from API:
result : [{"users":["[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})","[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})","[object] (App\\User: {\"username\":\"Alex\",\"id\":123458})","[object] (App\\User: {\"username\":\"Sky\",\"id\":1234569})","[object] (App\\User: {\"username\":\"Kvin\",\"id\":123460})"]}] []
One thing is your JSON return from API who is not well formatted.
[{
"users":[
"[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})",
"[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})",
...
]
}]
should be
[{
"users":[
{"username":"Kaki","id":123456}),
{"username":"(Alan)","id":123457}),
...
]
}]
I don't know what is Select2 version you use, but > 4 is advice.
Use functions templateResult and templateSelection is better, later you can return HTML for nicer rendering.
You can use this snipplet demo.
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
It is my first time using the plugin and .validate() method. Now I have a form and every time I click the submit button it runs with out doing the form validation. Here is my code:
<form class="form d" method="post" action="">
<input type="text" name="searchtitle" id="searchtitle" placeholder="Enter the textbook's title">
<input type="text" name="searchauthor" id="searchauthor" placeholder="Enter the textbook's author">
<input type="text" name="searchpublisher" id="searchpublisher" placeholder="Enter the textbook's Publisher">
<input type="text" name="searchedition" id="searchedition" placeholder="Enter the textbook's edition">
<select name="searchuniversity" id="searchuniversity"></select>
<select name="searchuniversitycampus" id="searchuniversitycampus" ></select>
<input type="submit" id ="searchsubmit" name="searchsubmit" value="Search">
</form>
I then have the following Javascript:
$(document).on('pageinit',"#searchpage",
//this funciton will carry out the things we need to do to carry out our search
function(e)
{
e.preventDefault();
$(".form.d").validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
comments: {
required: true,
minlength: 5,
nourl: true
}
},
messages: {
name: "Required Field",
email: "Valid Email Required",
comments: "Required Field + No URL's"
}
});
$("#searchsubmit").click(
function(e)
{
//Do a lot of processing here
});
});
Like I said I'm very new to doing the forma validation and using the function.
Here is a jsFiddle of the problem. When you click on submit in the fiddle it alerts "hello" and then it does the validation. How to stop this from happening. i.e validate first 1st and then run the function?
Your whole problem is your click handler. The plugin already has callback functions built in that will capture the click event of the submit button. Use the submitHandler to fire a function when the form is valid. Use the invalidHandler to fire a function when the form is invalid.
You already have the submitHandler callback in your jsFiddle so I refactored your jsFiddle code as follows:
$(document).on('pageinit', function(){
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true
},
field2: {
required: true
}
},
submitHandler: function (form) {
alert("hello"); // stuff to do when form is valid
alert('valid form submitted'); // for demo
return false;
},
invalidHandler: function () {
// stuff to do when form is invalid
alert("invalid form"); // for demo
}
});
// remove click handler
// use the plugin's built-in callback functions instead
//$("#test").click(function(){alert("hello")});
});
DEMO: http://jsfiddle.net/BTwaP/1/
See documentation for all callback functions
EDIT:
As of jQuery Mobile version 1.4, the pageinit event has been deprecated and replaced with pagecreate.
Good Reference: https://stackoverflow.com/a/14469041/594235
I'm using the MVC4 Ajax helper functions on a form and I'd like to submit the form from script.
The problem is when I call the submit function, it does not load into the proper div. Any thoughts?
#using (Ajax.BeginForm("NewGame", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "targetDiv" }, new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
<a class=button onclick="$('#newGameForm').submit();">New Game</a>
}
Clicking the standard submit button load the results of the call into the targetDiv. Clicking on the anchor replaces the current div.
The key is to prevent default browser behavior via .preventDefault() or to return false at the end of the event handlers.
This is how I'd do it:
<div id="targetDiv"></div>
#using(Html.BeginForm("NewGame", "Home", FormMethod.Post,
new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
}
<script type="text/javascript">
$(document).ready(function () {
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
type: $(this).attr("method") // "POST"
})
.done(function(result) {
$("#targetDiv").html(result);
})
.fail(function((jqXHR, textStatus, errorThrown) {
// handle error
});
});
});
</script>
If you insist on using an anchor <a>...
New Game
<script type="text/javascript">
$(document).ready(function() {
$("#submit-link").on("click", function(e) {
e.preventDefault();
$("#newGameForm").submit();
});
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
...
});
});
</script>
Edit There is also an AjaxHelper.ActionLink method. If you're already using the AjaxHelper in other parts of your code you might want to stick with that.
Pseudo Code.
<a class=button onclick="PostAjax();">New Game</a>
function PostAjax(){
$.ajax({
url:"Home/NewGame",
data:$('#newGameForm').serialize(),
DataType:"HTML", // assuming your post method returns HTML
success:function(data){
$("#targetDiv").html(data);
},
error:function(err){
alert(err);
}
})
}
I have this code snippet where I am passing data to another jsp file.
Javascript
$(document).ready(function() {
$("#click").click(function() {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type : "POST",
url : "pageTwo.jsp",
data : "name=" + name + "&age=" + age,
success : function(data) {
$("#response").html(data);
}
});
});
});
HTML
<body>
Name:<input type="text" id="name" name="name">
<br /><br />
Age :<input type="text" id="age" name="age">
<br /><br />
<button id="click">Click Me</button>
<div id="response"></div>
</body>
and in pageTwo.jsp, my code is
<%
String name = request.getParameter("name");
String age = request.getParameter("age");
out.println(name + age);
%>
but this is not working.Is any mistake in my Jquery ?.Can any one please help me?.
$("#click").click(function(e) {
// e.preventDefault();
...
return false;
});
and of course install firebug or use chrome default developer tools (f12). open console and run the code.
$(document).ready(function () {
$("#click").click(function () {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type: "POST",
url: "pageTwo.jsp",
data: "{'name':'" + name + "','age':'" + age + "'}",
contentType: "application/json",
async: false,
success: function (data) {
$("#response").html(data.d);
}
});
});
});
im working on this jquery data entry form in which i need a specific field to be autocompleted with data from mysql
i got everything working, autocomplete retrieves data from the sql through php matching is great in english/latin and utf8 characters
the values get retrieved from the sql as "'number' => 'name'"
right now the autocomplete has 3 values in the output, value, label and id.
as id and value it uses the 'name'
and the label is the 'number' of my sql string (which is posted to the next page when the form is submited)
so everyting works ok, my 'number' is posted correctly, there is a minor annoyance tho
when i select something from the autocomplete list, the field is populated with the 'number'
is there any way to fill it with the 'name'?
ie: search for 'name', get dropdown with 'names', click and get the 'name' in the field, and when i submit i get the 'number' posted?
any help would be greatly appreciated.
if you need to take a look at my code, it's posted on a previous question: Jquery ui - Autocomplete - UTF8 charset
thanx in advance :)
The usual way to do this is:
Use a hidden input to hold the value you'd like to POST, then autocomplete a separate field.
Populate the hidden input on select
Populate the visible, autocompleted input with the label property of the item that was selected.
So, for example:
HTML:
<input type="hidden" name="name" />
<input type="text" id="name_auto" />
JavaScript:
$(function () {
var cache = {},
lastXhr;
$( ".name" ).autocomplete({
minLength: 1,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
},
select: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
},
change: function (event, ui) {
if (ui.item) {
$("input[name='name']").val(ui.item.value);
} else {
$("input[name='name']").val('');
}
}
});
});
You can use the result (handler) from u'r autocomplete
where the variable data such as arrays and you can return two data at once
Expl:
in javascript
$().ready(function()
{
var url = "<?=base_url()?>index.php/master/agen";
var width_val = 308;
$("#name_auto").autocomplete(url,
{
width: width_val,
selectFirst: false,
});
$("name_auto").result(function(event, data, format)
{
$("#name_auto").val(data[0]);
$("#id").val(data[1]);
});
});
in HTML :
<input type="hidden" name="number" id="id" />
<input type="text" id="name_auto" name="name" />
in PHP :
foreach ($source->result() as $row)
{
echo "$row->nama|$row->id\n";
}
note : here I use PHP CodeIgniter in its