Set initial JQuery suggest value - javascript

I have a JQuery suggest box using a key and a value. The key is the saved value, for example a userId and the value is the shown value such as a username.
When having a blank field it works great. I type a few characters, select a name and the value is added as the value that is posted with the HTTP request. Now, how should I prefill a form's suggest with when it already has a value. When placing the saved userId as the value the suggest shows the userId but, obviously I want to show the username. I also tried to echo the username that was selected but than, if the username is not changed the posted value will be the username.
<script>
<!--
$(document).ready(function() {
$("#creatorUserId").autocomplete("Gateway.php?action=UserAction&subAction=suggest",{
parse: function(data) {
var parsed = [];
data = data.data;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
value: data[i].key,
result: data[i].value
};
}
return parsed;
},
formatItem:function(item, index, total, query){
return item.value;
},
formatResult:function(item){
return item.id;
},
dataType: 'json'
});
});
-->
</script>
<input type="text" name="creatorUserId" id="creatorUserId" value="3" size="40" />
How could I solve this?

Try this
<script>
<!--
$(document).ready(function() {
$("#creatorUserId").autocomplete("Gateway.php?action=UserAction&subAction=suggest",{
parse: function(data) {
var parsed = [];
data = data.data;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
key: data[i].key,
value: data[i].value
};
}
return parsed;
},
formatItem:function(item, index, total, query){
return item.value;
},
formatResult:function(item){
return item.id;
},
dataType: 'json'
});
});
-->
</script>

Deleting the current value of the text box on click (If and only if the text box has not yet been edited).
When the input looses focus, and if the input was un-edited, put the initial value back.

Related

How do I prevent my html select tag from populating with duplicate data, on every click?

When I click my <select> tag, then it sends an AJAX request to the server script, which returns an array of values, which then populate the dropdown. My code is as following:
HTML:
<p id="cln_cd">Colony code : <select name="colony_code" id="colony_code" style="max-width:90%;" onclick="get_code()">
<option value="" selected="selected_code">Select your colony code</option>
</select></p>
JS:
function get_code(){
var select = document.getElementById("colony_code");
$.ajax({
url : 'index_backend.php',
type : 'POST',
data : {"input":"code"},
success : function(response) {
var parsedResponse = JSON.parse(response);
parsedResponse = parsedResponse.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
}); //removes duplicates
for(var i=0; i<parsedResponse.length; i++){
var opt = parsedResponse[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
},
complete: function(){
}
});
}
Now, the more I press the <select> tag, the more the same data keeps on populating my dropdown menu.
To prevent this, I tried emptying my dropdown list before inserting data into it, like this:
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for(i = L; i >= 1; i--) {
selectElement.remove(i);
} //only the "Select your colony code" stays as default, rest is removed
}
function get_code(){
var select = document.getElementById("colony_code");
removeOptions(select);
$.ajax({
url : 'index_backend.php',
type : 'POST',
data : {"input":"code"},
success : function(response) {
var parsedResponse = JSON.parse(response);
parsedResponse = parsedResponse.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
}); //removes duplicates
for(var i=0; i<parsedResponse.length; i++){
var opt = parsedResponse[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
},
complete: function(){
}
});
}
Now, although my dropdown is not taking in duplicate values any more, but no matter what <option> value, I press, it just shows the Select your colony code option. I have no idea as to why this is happening. How do I fix this?
Firstly you have a mix of jQuery and plain JS methods in your code. It's best to stick to one or the other. As you've included the jQuery library in the page, you may as well stick with that to make the code more succinct.
With regard to the issue, I assume you're expecting to retain the current selected item when reloading the option elements. As such you need to save that value in a variable, remove the existing option, re-populate them and then re-assign the value. The code would look something like this:
function get_code() {
let $select = $("#colony_code");
$.ajax({
url: 'index_backend.php',
type: 'POST',
data: { "input": "code" }, // should 'code' be a variable...?
dataType: 'json', // add this property to avoid the need to call JSON.parse in success
success: function(response) {
let selectedValue = $select.val();
let html = response.filter((e, i, a) => a.indexOf(e) === i).map(item => `<option value="${item}">${item}</option>`);
$select.html(html).val(selectedValue);
},
complete: function() {}
});
}

JS: using ajax to check existing data in db on input typing

So I want to detect if the value a user is typing in an input exists in the database, if so, display an error message. I've gotten pretty close except when the input is empty, the empty value is being submitted instead of what is GOING to be typed.
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
})
});
I've also tried one with a keyup function and it's still doing the same, evaluating the empty field. How can I have it so it's constantly evaluating what is being typed?
Along the same lines as Jeff Puckett's answer, I would perform the empty test and return an instructional message if empty:
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
if (val.length < 1 || val==""){
alert('Please complete all fields');
$('#email').css('background','yellow').focus();
return false;
}
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
});
});
This snippet creates an input with the id of "in" and checks if there is something in in's value. I guess that is answering your question a bit more specifically. And thanks "Jeff Puckett II" for pointing this out.
$('#in').on('input focusout', function(){
var val = $('#in').val();
if (val != ""){
console.log('someones typing');
} else {
console.log('empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="in" type="text">
</body>
try .on('input') instead of .on('blur')
$("#email").on("input", function(){//do something});
//in your function just add
if(!val) {
$(".error-msg").text("Empty!");
}
//or
if(val) {
//your ajax code
}
simply check if input is empty first
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
// check if val is empty
if (val != "")
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
})
});
use this:
$('input').keyup(function(){
console.log($(this).val());
});
keyup or keydown to get data every time when a user type in the focused input.

Get select multiple values with JQuery

I have a problem with JQuery, I have a multiple select that i can populate in 2 ways, manually taking some value from another select with a add button, and dynamically, with parsing a json returned from a spring call.
I have no problem to take the value when I add it manually, but, when I populate dynamically the select, the JQuery code doesn't take any value although int the html code there're values in the select.
Here my code:
The empty html selects
<div id="enti_disp_box">
<label>Enti disponibili</label>
<select id="ente" multiple> </select>
<button class="btn" onclick="addEnteInBox();" type="button">Aggiungi</button>
</div>
<div id="enti_att_box">
<label>Enti attivi*</label>
<select id="entiAttivi" multiple></select>
<button class="btn" onclick="removeEnteInBox();" type="button">Rimuovi</button>
</div>
JQuery for populate the second select manually
function addEnteInBox(){
var selectedOptions = document.getElementById("ente");
for (var i = 0; i < selectedOptions.length; i++) {
var opt = selectedOptions[i];
if (opt.selected) {
document.getElementById("entiAttivi").appendChild(opt);
i--;
}
}
}
function removeEnteInBox(){
var x = document.getElementById("entiAttivi");
x.remove(x.selectedIndex);
}
JQuery for populate the second select dynamically
function getEntiByIdUtente(idutente) {
var action = "getEntiByidUtente";
var payload = {
"idUtente": idutente,
"action": action,
"token": token
};
$.ajax({
type: "POST",
url: '../service/rest/enti/management_utenti',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(payload),
resourceType: 'json',
success: function(obj, textstatus) {
obj = obj.trim();
var json = JSON.parse(obj);
//parse response
if (obj.stato == 'error') {
alert('Errore');
} else {
$('#entiAttivi').empty();
//fetch obj.data and populate table
$(json.data).each(function() {
$("#piva").val(this.piva);
$("#codiceipa").val(this.codiceipa);
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
});
}
return json;
},
error: function(obj, textstatus) {
alert('Errore di comunicazione col server!');
}
});
}
JQuery for taking the value of the second select
var entiList = $("#entiAttivi").val();
This line seems to be wrong, it's not working for me
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
would you try replacing by
$('#entiAttivi').append($('<option value="' + this.idente + '">' + this.regionesociale + '</option>');
The append, is trying to create an option with the json as parent, this is not working. please try my code.

Text Area interfering with Ajax Code

I am just trying to clear the text area with an id of "discussion" it clears the textbox but it does not load the data from the server with the ajax statement. When I remove the line that clears that text area it loads all the data in fine but just adds to the current data.
Here is my code:
function LoadRoomMessages(id)
{
$.ajax(
{
type: "Get",
url: "#Url.Action("GetMessages", "Home")",
data: { roomId: id },
success: function (data)
{
// Here is the line that causes issues.
$('#discussion').val('');
json = data;
var obj = JSON.parse(json);
for (var i = 0; i < data.length; i++)
{
$('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "\r\n");
}
}
});
}
You may also try (as you asked to answer it)
$('#discussion').empty();

Send form data using ajax

I want to send all input in a form with ajax .I have a form like this.
<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>
And in .js file we have following code :
function f (form ,fname ,lname ){
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
But this is not working.i don't want to use Form data .
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
In your function form is a DOM object, In order to use attr() you need to convert it to jQuery object.
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, {fname : fname , lname :lname}).done(function (data) {
alert(data);
});
return true;
}
With .serialize()
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, $(form).serialize() ).done(function (data) {
alert(data);
});
return true;
}
Additionally, You can use .serialize()
$.ajax({
url: "target.php",
type: "post",
data: "fname="+fname+"&lname="+lname,
}).done(function(data) {
alert(data);
});
I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
Following part of the function might be of interest:
if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
//Get all the input elements in form
var elem = data.elements;
//Loop through the element array
for(var i = 0; i < elem.length; i++) {
//Ignore elements that are not supposed to be sent
if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
continue;
//Add & to any subsequent entries (that means every iteration except the first one)
if(data_string.length>0)
data_string+="&";
//Get data for selectbox
if (elem[i].tagName.toUpperCase() == "SELECT")
{
data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
}
//Get data from checkbox
else if(elem[i].type=="checkbox")
{
data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
}
//Get data from textfield
else
{
data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
}
}
return data_string;
}
It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.
Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:
function ajax_create_request_string(data, recursion) {
var data_string = '';
//Zpracovani formulare
if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
//Get all the input elements in form
var elem = data.elements;
//Loop through the element array
for(var i = 0; i < elem.length; i++) {
//Ignore elements that are not supposed to be sent
if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
continue;
//Add & to any subsequent entries (that means every iteration except the first one)
if(data_string.length>0)
data_string+="&";
//Get data for selectbox
if (elem[i].tagName.toUpperCase() == "SELECT")
{
data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
}
//Get data from checkbox
else if(elem[i].type=="checkbox")
{
data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
}
//Get data from textfield
else
{
if(elem[i].className.indexOf("autoempty")!=-1) {
data_string += elem[i].name+"=";
}
else
data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
}
}
return data_string;
}
//Loop through array
if(data instanceof Array) {
for(var i=0; i<data.length; i++) {
if(data_string!="")
data_string+="&";
data_string+=recursion+"["+i+"]="+data[i];
}
return data_string;
}
//Loop through object (like foreach)
for(var i in data) {
if(data_string!="")
data_string+="&";
if(typeof data[i]=="object") {
if(recursion==null)
data_string+= ajax_create_request_string(data[i], i);
else
data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
}
else if(recursion==null)
data_string+=i+"="+data[i];
else
data_string+=recursion+"["+i+"]="+data[i];
}
return data_string;
}
The code you've posted has two problems:
First: <input type="buttom" should be <input type="button".... This probably is just a typo but without button your input will be treated as type="text" as the default input type is text.
Second: In your function f() definition, you are using the form parameter thinking it's already a jQuery object by using form.attr("action"). Then similarly in the $.post method call, you're passing fname and lname which are HTMLInputElements. I believe what you want is form's action url and input element's values.
Try with the following changes:
HTML
<form action="/echo/json/" method="post">
<input type="text" name="lname" />
<input type="text" name="fname" />
<!-- change "buttom" to "button" -->
<input type="button" name="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " />
</form>
JavaScript
function f(form, fname, lname) {
att = form.action; // Use form.action
$.post(att, {
fname: fname.value, // Use fname.value
lname: lname.value // Use lname.value
}).done(function (data) {
alert(data);
});
return true;
}
Here is the fiddle.
you can use serialize method of jquery to get form values. Try like this
<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form) " >
</form>
function f( form ){
var formData = $(form).serialize();
att=form.attr("action") ;
$.post(att, formData).done(function(data){
alert(data);
});
return true;
}
can you try this :
function f (){
fname = $("input[name='fname']").val();
lname = $("input[name='fname']").val();
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
}

Categories