Set automatically value in a textbox after autocomplete javascript - javascript

I have 4 textbox that are connected each other in my database, the values are: Name surname, team, society, country.
I have already created an autocomplete method for all the values; infact if i try to write a name/society ecc, the method search in the database if the values exist and recommend values. Another thing that i have already implemented is that if I select a name surname and a team (or other 2 values) it suggests you society and country or what you did not select that are collegated with the other values.
What do i have to do to set automatically the values, without using the select of the user(what i have to do to set automaticcaly the textbox value of the result of the query)? Thank you.
I am using Asp.net mvc and javascript.
Edit: this the code.
Html:
#{
string autocompletePrefix = "address";
}
<div class="form-group">
#Html.CustomLabelFor(model => model.PlayerId, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="display:inline-flex;">
<div class="input-group">
#Html.TextBox("Player", null, null, new { #id = autocompletePrefix + "PlayerName", #class = "ui-autocomplete-input form-control" })
<span class="input-group-btn">
<button id="#autocompletePrefix-PlayerSearcher" class="btn btn-default" type="button">
<span class="glyphicon glyphicon-list" id="#autocompletePrefix-playerIconList"></span>
</button>
</span>
</div>
<div class="ui-autocomplete ui-front btn-group-vertical"></div>
#Html.HiddenFor(model => model.PlayerId, new { #id = autocompletePrefix + "PlayerId" })
#Html.ValidationMessageFor(model => model.PlayerId)
</div>
</div>
<script type="text/javascript">
$(document).on('ready readyAgain', function () {
address = AutocompleteTeamModule('#autocompletePrefix', '#Url.Action("GetHintsForPlayers", "Addresses", new { })', '#Url.Action("GetHintsForTeam", "Addresses", new { })', '#Url.Action("GetHintsForSocieties", "Addresses", new { })', '#Url.Action("GetHintsForCountry", "Addresses", new { })');
initMultipleSelection();
});
</script>
Javascript:
function AutocompleteTeamModule( _prefixHtmlId, _hintsForPlayer,_hintsForTeam,_hintsForSociety,_hintsForCountry)
{
init: function () {
$("#" + myObj.prefixHtmlId + "-PlayerSearcher").click(function () {
myObj.PlayerSearcherClick = true;
$('#' + myObj.prefixHtmlId + 'PlayerName').autocomplete("option", "minLength", 0);
var value = $("#" + myObj.prefixHtmlId + "PlayerId").val();
if( value != "")
$('#' + myObj.prefixHtmlId + 'PlayerName').autocomplete("search", $("#" + myObj.prefixHtmlId + "PlayerId").val());
else
$('#' + myObj.prefixHtmlId + 'CountryName').autocomplete("search", "");
$('#' + myObj.prefixHtmlId + 'PlayerName').trigger("focus");
$("#" + myObj.prefixHtmlId + "-PlayerLoader").toggleClass("hide", false);
$("#" + myObj.prefixHtmlId + "-PlayerIconList").toggleClass("hide", true);
$("#" + myObj.prefixHtmlId + "-PlayerCountry").toggleClass("hide", false);
$('#' + myObj.prefixHtmlId + 'PlayerName').autocomplete("option", "minLength", 2);
});
$("#" + myObj.prefixHtmlId + "PlayerName").autocomplete({
minLength: 2, autoFocus: true, source: function (term, resp) {
$.ajax({
type: "GET",
url: myObj.hintsPlayerUrl,
data: { "id": term.term + "-" + $("#" + myObj.prefixHtmlId + "PlayerId").val() },
success: function (data) {
$("#" + myObj.prefixHtmlId + "-PlayerLoader").toggleClass("hide", true);
$("#" + myObj.prefixHtmlId + "-PlayerIconList").toggleClass("hide", false);
myObj.PlayerNameData = data.slice();
resp(data, function (data) {
return data;
});
},
error: function (xhr, txt, err) {
iride_error_handler(xhr, txt, err);
}
})
},
select: function (e, data) {
var pa=$("#" + myObj.prefixHtmlId + "PlayerId").val();
$("#" + myObj.prefixHtmlId + "PlayerId").val(data.item.value);
$("#" + myObj.prefixHtmlId + "-PlayerLoader").toggleClass("hide", true);
$("#" + myObj.prefixHtmlId + "-PlayerIconList").toggleClass("hide", false);
pa = data.item.value;
e.preventDefault();
var teamisSet = $("#" + myObj.prefixHtmlId + "TeamId").val();
if (teamisSet == "")
$('#' + myObj.prefixHtmlId + 'TeamName').autocomplete("search", "-" + pa);
e.preventDefault();
var societyisSet = $("#" + myObj.prefixHtmlId + "SocietyId").val();
if (provinceisSet == "")
$('#' + myObj.prefixHtmlId + 'ProvinceName').autocomplete("search", "-" + pa);
e.preventDefault();
var countryisSet = $("#" + myObj.prefixHtmlId + "CountryId").val();
if(countryisSet == "")
$('#' + myObj.prefixHtmlId + 'CountryName').autocomplete("search", "-" + $("#" + myObj.prefixHtmlId + "CountryId").val());
e.preventDefault();
},
focus: function (event, ui) {
if (ui.item.value != " ") {
$(this).val(ui.item.label);
}
event.preventDefault();
}
});
}

You might provide some code samples or be more specific in what components you are using.
Maybe you can use just jQuery (javascript):
$('#textboxID').val('new value of textbox');

Elaborating on the JQuery suggestion-
I'd definitely like to see some code but based on what I think your code looks like,
If you're talking about changing the value of selectors based on user input on other selectors, you can use a switch or if else inside your click handler. If this is a very data-heavy process there's sure to be a more efficient way to do it but if this is small enough it would go something like this-
$('submitbutton').click(function() {
if ($('firstselector').val() == 'certain value') {
$('secondselector').val("associated value 1");
$('thirdselector').val("associated value 2");
} else if ($('firstselector').val() == 'another certain value') {
// so on and so forth
};
});
a switch, if too many options available- to clean up the code
$('submitbutton').click(function() {
switch ($('firstselector').val()) {
case: 'certain value'
$('secondselector').val("associated value 1");
$('thirdselector').val("associated value 2");
break;
case: 'another certain value'
// so on and so forth
break;
};
});

Related

how Allow duplicates selection in select2 with tag editor

Im add duplicates tags with item in Select2 input?
but dont allow add new tag input .
when new tag dont allow.
You have to choose item from dropdown.
this my pic
dont allow tag
test
to add dropdown
this my code:
$("#AutoMessage").select2({
width: '100%',
dir: "rtl",
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term + $("#AutoMessage").val(),
newOption: true
}
},
templateResult: formatResultData
});
function formatResultData(data) {
if (!data.id) {
var $result = $("<span></span>");
$result.text(data.text);
return $result;
// $("#AutoMessage").append('<option value="' + e.params.data.text + '">' + e.params.data.text + '</option>');
};
if (data.element.selected) return;
return data.text;
};
$("#AutoMessage").on("select2:select", function (e) {
var data = e.params.data;
//alert("as");
//if ((e.currentTarget).find("option[value='" + data.id + "']").length == 0)
// return;
$("#AutoMessage").append('<option value="' + e.params.data.text + '">' + e.params.data.text + '</option>');
});
$("#AutoMessage").on("select2:unselect", function (e) {
var data = e.params.data;
//if ($(e.currentTarget).find("option[value='" + data.id + "']").length > 0)
// return;
e.params.data.element.remove();
});

How to convert the values in an array to strings and send to php?

I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.

Updating <li> text using JSON data

I trying to update dynamically added li text (html code) with the JSON data as below script, but the update method are not working, could you help me to check?
City
<input type="text" id="cinput">
<br>
<input type="button" id="cadd" value="Add">
<input type="button" id="cup" value="Update">
<div class="clista">
<ul class="lista inset" id="citem">
<li data-val="Campinas">Campinas [T:00ºC H:00%] <span style="float:right;"><b>[X]</b></span>
</li>
<li data-val="Sao Paulo">Sao Paulo [T:00ºC H:00%] <span style="float:right;"><b>[X]</b></span>
</li>
</ul>
</div>
Javascript
$("#cadd").on("click", function () {
var cinput = document.getElementById("cinput").value;
var msg = "'Remover?'";
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + cinput + "&units=metric", function (data) {
var cdados = ('T:' + data.main.temp + 'ºC H:' + data.main.humidity + '%');
$('#citem').append('<li data-val="' + cinput + '">' + cinput + " [" + cdados + ']<a href="#" onclick="if(confirm(' + msg + ')){parentNode.parentNode.removeChild(parentNode)}"> <span style="float:right;"><b>[X]</b></span></li>');
document.getElementById("cinput").value = "";
});
});
$("#cup").on("click", function () {
var cidade = '';
var oldText = '';
var novotxt = '';
var msg = "'Remover?'";
var Link = (' <span style="float:right;"><b>[X]</b></span>');
$('.clista li').each(function () {
var $this = $(this);
cidade = $(this).data('val');
oldText = $(this).html();
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + cidade + "&units=metric", function (data) {
var cdados = ('T:' + data.main.temp + 'ºC H:' + data.main.humidity + '%');
novotxt = cidade + " [" + cdados + "] ";
alert(novotxt);
$this.html(function (index, html) {
return html.replace(oldText, novotxt + Link);
});
});
});
});
jsFiddle here: http://jsfiddle.net/fabiobraglin/rcheaowx/21/
You're hitting an asynchronous issue here. You have $.each and within that you're setting oldText and trying to use it's value within the callback of getJSON. However, the entirety of the $.each loop will run before any of the getJSON callbacks are run, so oldText will end up being set to the final element in the collection for ALL of the callbacks, so it will only ever be correct for the final element.
There's two things to note here: the html parameter of this callback:
$this.html(function (index, html) {
return html.replace(oldText, novotxt + Link);
});
should be functionally equivalent to what you're trying to use oldText for. However, the element's contents are also cleared out before this callback is run, and whatever you return from it will be the entire contents of the element, so there's no need to try to replace the oldText in this way. Just return your new content:
$this.html(function (index, html) {
return novotxt + Link;
});
If you do find youself in a situation where the variables from the loop need to be available within the callback, you can create a closure as follows:
$('.clista li').each(function () {
var $this = $(this);
cidade = $(this).data('val');
oldText = $(this).html();
(function getData(_oldText, _cidade) {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + _cidade + "&units=metric", function(data) {
var cdados = ('T:' + data.main.temp + 'ºC H:' + data.main.humidity + '%');
novotxt = _cidade + " [" + cdados + "] ";
alert(novotxt);
$this.html(function(index, html) {
return html.replace(_oldText, novotxt + Link);
});
});
})(oldText, cidade);
});

Content disappears from jQuery autocomplete when focus on field is lost

my autocomplete works fine, but problem appears when I want to skip to another field in my form. When autocomplete lose focus its value disappears (also value of span that I render after this autocomplete disappears).
function initCaAutocomplete() {
$(".caSelector").autocomplete({
source: "/core/index/search-ca/ajax/1",
minLength: 2,
select: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
if ($('span#' + descId).length) {
$('span#' + descId).html(ui.item.desc);
$('span#' + descId).attr('title', ui.item.fullDesc);
} else {
$(this).after('<span title="' + (ui.item.fullDesc) + '" class="cpv_descHolder" id="' + descId + '">'
+ ui.item.fullDesc + '</span>');
}
ui.item.value = ui.item.code;
$('.tooltip', $(this).parent()).hide();
},
change: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
var inputId = $(this).attr('id');
var source = $(this).val();
$.ajax({
type : 'POST',
url : '/core/index/search-ca/ajax/1',
dataType: "text",
async : true,
data : {
term: source
},
success: function (response) {
var codes = $.parseJSON(response);
if (codes.length == 0) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
},
error: function (response) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
});
},
position: { my : "left top", at: "left bottom" }
});
}

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories