JQUERY SELECT AJAX - javascript

the following code works fine for me to show various sql-results after change a select-field:
$(document).ready(function() {
$('#main_kat').change(getDropdownOptions);
});
function getDropdownOptions() {
var val = $(this).val();
$.post('/ajax/joe.php?qid=<? echo $row_job['sub_quali'];?>', { value : val}, populateDropdown, 'html');
$("#send").prop('disabled', false);
}
function populateDropdown(data) {
if (data != 'error') {
$('#subcat').html(data);
}
}
my problem: for a new insert everything is great because i have to select manualy, but if i use this code for my update form, i want to have opend my div #subcat allready.
i tried following at the beginning:
kat = $('#main_kat').val();
getDropdownOptions(kat);
kat is set (checked) via alert, but the function will not be fired... where is my mistake ?
Thanks

you can not just call the function because you are using it with this.
kat = $('#main_kat').val();
getDropdownOptions(kat);
function getDropdownOptions() {
var val = $(this).val();
change to:
getDropdownOptions();
function getDropdownOptions() {
var val = $(document.getElementById('main_kat')).val();

It will probably work fine if you ensure that the this reference points to the correct object when you call the function. Instead of passing kat as a parameter you could just call the getDropdownOptions method with the following code:
getDropdownOptions.apply(kat);

I'll recommend you to replace your getDropdownOptions function by this:
function getDropdownOptions(val) {
val = val || $('#main_kat').val();
$.post('/ajax/joe.php?qid=<? echo $row_job['sub_quali'];?>', { value : val}, populateDropdown, 'html');
$("#send").prop('disabled', false);
}

Related

How can I replace the name attribute

I have this PHP output:
$total.":".$newId;
When success the function live_update() echo response back. I need to split PHP output into $total & $newId and change the existing input name attribute to the $newId. To do this, I tried my best for hours but I didn't succeed. Any help will be highly appreciated. This is the live_update() function:
<script>
function live_update(el) {
var str = el.value ;
var id = el.id ;
var name= el.name;
if (str.length==0) {
document.getElementById("live_update").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
var Resp = this.responseText;
var SplitedId = id.split(".");
if(SplitedId[1] == "di")
{
var Fres = Resp.split(":");
document.getElementsByName(name).name=Fres[1];
var Total = Fres[0];
}else{
var Total = Resp;
}
if (this.readyState==4 && this.status==200) {
document.getElementById("live_update").innerHTML=Total;
document.getElementsByName("coupon_row").style.disabled='none';
}
}
xmlhttp.open("GET","profiles.php?act=live_update&u_key={u_key}&name="+name+"&id="+id+"&q="+str,true);
xmlhttp.send();
}
</script>
Change
document.getElementsByName(name).name=Fres[1];
to
document.getElementsByName(name)[0].setAttribute('name', Fres[1]);
guessing that you want a way to change name of a single element. you can do as above.
if there are multiple elements with same name, simply iterate and change name with
el.setAttribute('name', Fres[1])
Hope it works!
You should use the setAttribute() method to set a name to a HTML element. So, this is how it goes,
document.getElementsByName(name)[0].setAttribute("name", Fres[1]);
And document.getElementsByName() returns a list of elements so since you need the first element gotta use [0] index and set the name as shown.
If you want to update the same element you passed in live_update(el) you can simply do this
el.setAttribute("name", Fres[1]);

Bootstrap typeahed is one character behind using jquery

I am using bootstrap typeahead (GitHub) to create search forms. After user inputs something I am doing elasticsearch query using elasticsearch.js and returning results. The problem is that results displayed in typeahead are always one character behind, not suggesting correct values.
Typeahead input:
<input type="text" data-provide="typeahead" class="form-control typeahead" id="searchInputId" placeholder="Search" autocomplete="off">
Here is my code:
var elasticsearchAddress = "exampleserver.com:9200";
var elasticsearchClient = createElasticsearchClient(elasticsearchAddress);
var data = [];
$("#searchInputId").typeahead({ source:data, items:10, fitToElement:true });
$("#searchInputId").on("input", function(){
var searchTerm = $("#searchInputId").val();
elasticsearchMathPhrasePrefixSearch(elasticsearchClient, searchTerm, function () {
$("#searchInputId").data('typeahead').source = getElasticsearchSearchResultsArray();
});
});
elasticsearchMathPhrasePrefixSearch() function
function elasticsearchMathPhrasePrefixSearch(client, searchPhrase, callback) {
console.log("Searching for: " + searchPhrase);
client.search({
body: {
"query": {
"match_phrase_prefix": {
"accountName": searchPhrase
}
}
}
}, function (error, response) {
if (error) {
console.trace('ELASTICSEARCH: Search query failed');
} else {
console.log('ELASTICSEARCH: Search query OK');
var doc = response.hits.hits;
elasticsearchSearchResultsArray = getDocs(doc);
}
callback();
});
}
getDocs() function
function getDocs(doc){
var searchResultsArray=[];
for(var i = 0; i < doc.length; i++){
searchResultsArray.push(doc[i]._source.accountName);
}
return searchResultsArray;
getElasticsearchSearchResultsArray() function
function getElasticsearchSearchResultsArray(){
return elasticsearchSearchResultsArray;
}
elasticsearchSearchResultsArray is a global array that holds the results. Because of the JS async nature I had no other idea to make it work.
EDIT:
Ok, I modified my code so the source is updated correctly with help of this Issue #1997. But now I have got another problem. The typeahead dropdown is not displayed when I type.
My new code:
var empty = [];
$("#searchInputId").typeahead({ source:empty, items:10, fitToElement:true });
$("#searchInputId").on("keyup", function(ev){
ev.stopPropagation();
ev.preventDefault();
//filter out up/down, tab, enter, and escape keys
if( $.inArray(ev.keyCode,[40,38,9,13,27]) === -1 ){
var self = $(this);
//set typeahead source to empty
self.data('typeahead').source = [];
//active used so we aren't triggering duplicate keyup events
if( !self.data('active') && self.val().length > 0){
self.data('active', true);
//Do data request. Insert your own API logic here.
var searchTerm = self.val();
elasticsearchMathPhrasePrefixSearch(elasticsearchClient, searchTerm, function() {
//set this to true when your callback executes
self.data('active',true);
//set your results into the typehead's source
self.data('typeahead').source = getElasticsearchSearchResultsArray();
//trigger keyup on the typeahead to make it search
self.trigger('keyup');
//All done, set to false to prepare for the next remote query.
self.data('active', false);
});
}
}
});
Try to use on("keyup") instead. input is 1 character behind.
Ok, I resolved it myself. I switched from bootstrap3-typeahead to jQuery UI Autocomplete. It is working great and the script is much smaller.
New code:
$("#searchInputId").on("keydown", function () {
$("#searchInputId").autocomplete({
source: function(request, response) {
var searchTerm = $("#searchInputId").val();
elasticsearchMathPhrasePrefixSearch(elasticsearchClient, searchTerm, function (){
response(getElasticsearchSearchResultsArray());
});
}
});
});

Javascript save , erase and reload input value

I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};

Trying to create/bind onClick event to <option> generated through a dojo.xhrGet request

I'm trying to make a piece of dojo Code work and having a bit of a hard time.
The intention behind it goes like this:
1- Have a select fire an onChange event that retrieves a list of options through dojo.xhrGet.
2- Have each one of the options retrieved get its own onclick event associated/binded to it and the function that it fires takes 2 arguments
Problem: At this point the onClick event on the options fires as soon as it is retrieved through Ajax and doesn't pass the firt argument. The events stop firing after that (a click produces nothing).
Thank you for your feedback in advance. The Code follows
JS
function checkAvailable(i){
var id_prog = 'programa_'+i;
var id_coreo = 'coreografia_'+i;
var prog = dojo.byId(id_prog).value;
dojo.xhrGet({
url:"ajaxCoreo.php",
handleAs:"text",
content: {
programa: prog,
item: i
},
load: function(data){
var targetNode = dojo.byId(id_coreo);
dojo.place(data,targetNode,"only");
dojo.byId(id_coreo).disabled = false;
var callback = function(evt){
var j = evt.target.innerHTML;
checkPack(j,i);
console.log('write me if you fire inside first function');
};
dojo.query("#coreografia_1>option").connect('click', callback);
setValor(i);
}
});
}
function checkPack(j,i){
console.log('write me if you fire inside second function');
console.log(j);
console.log(i);
var num = j;
var id_prog = 'programa_'+i;
var id_coreo = 'coreografia_'+j;
var prog = dojo.byId(id_prog).value;
dojo.xhrGet({
url:"ajaxPack.php",
handleAs:"text",
content: {
programa: prog,
coreo: j
},
load: function(data){
if(data=="true"){
dojo.query("option[value="+num+"]").forEach(dojo.destroy);
alert('O Pack escolhido já foi encomendado previamente.');
setValor(i);
}
}
});
}
HTML
<select name="programa[]" id="programa_1" onChange="checkAvailable(1)" title="obrigatorio">
<option value="0">Choose your program</option>
</select>
<select name="coreografia_1" id="coreografia_1" disabled="disabled" title="obrigatorio">
<option value="0" selected="selected">Escolha Um Programa</option> //this is the node that is populated by the first xhrGet call
</select>
EDIT: I've edited the code to reflect the changes to it and added the html
By inspecting your code, i can see that in the function checkAvailable, in the line where you connect to onclick event instead of passing the function as callback you are calling it.
dojo.connect(opt,'onclick', checkPack(opt.target.innerHTML,i));
You should do something like this:
var callback = function(){
checkPack(opt.target.innerHTML,i);
};
dojo.connect(opt,'onclick', callback);
From my experience, if you spend more than 1 day trying to track a cross-brower issue it's probably somewhere on your basic html knowledge or your basic Js concepts.
This one was related to the fact that only FF manages onclick events directly attached to option tag. For the rest of the gang you need to attach the onchange to the parent.
So here is the final version of the working code, in case anyone comes upon a similar issue
function checkAvailable(i){
var id_prog = 'programa_'+i;
var id_coreo = 'coreografia_'+i;
var prog = dojo.byId(id_prog).value;
dojo.xhrGet({
url:"ajaxCoreo.php",
handleAs:"text",
content: {
programa: prog,
item: i
},
load: function(data){
var targetNode = dojo.byId(id_coreo);
dojo.place(data,targetNode,"only");
dojo.byId(id_coreo).disabled = false;
var callback = function(evt){
var j = evt.target.value;
checkPack(j,i);
};
dojo.query("#coreografia_"+i).connect('onchange', callback);
setValor(i);
}
});
}
function checkPack(j,i){
console.log('write me if you fire inside second function');
console.log(j);
console.log(i);
var num = j;
var id_prog = 'programa_'+i;
var id_coreo = 'coreografia_'+j;
var prog = dojo.byId(id_prog).value;
//Confirma Se não há encomendas previas deste pack (um máximo de 2 anteriores)
dojo.xhrGet({
url:"ajaxPack.php",
handleAs:"text",
content: {
programa: prog,
coreo: j
},
load: function(data){
if(data=="true"){
dojo.query("#coreografia_"+i+" option[value="+num+"]").forEach(dojo.destroy);
alert('O Pack escolhido já foi encomendado previamente.');
}
}
});
}

Two scripts Javascript doesn't work together

I have two scripts in a file active_form.js
The first script hides a text entry when a radiobutton is checked and the second does the same thing when a value is selected in a list.
When there are alone, the both work but together my function GereControleRadio do nothing.
edit : the two scripts are called in the same form.
The code of my scripts :
function GereControleRadio(Controleur, LabelControle, Controle, Masquer) {
var objLabelControle = document.getElementById(LabelControle);
var objControle = document.getElementById(Controle);
if (Masquer=='1') {
objControle.style.visibility=(objControleur.checked==true)?'visible':'hidden';
objLabelControle.style.visibility=(objControleur.checked==true)?'visible':'hidden';
}
else {
objControle.disabled=(objControleur.checked==true)?false:true;
objLabelControle.disabled=(objControleur.checked==true)?false:true;
}
return true;
};
function GereControleList(LabelControle, Controle, val) {
var objLabelControle = document.getElementById(LabelControle);
var objControle = document.getElementById(Controle);
if (val != '1% Patronal') {
objControle.style.visibility='hidden';
objLabelControle.style.visibility='hidden';
}
else {
objControle.style.visibility='visible';
objLabelControle.style.visibility='visible';
}
return true;
};
The .js is called in my view.yml
And I call the functions :
echo $form['etage']->render(array("onCLick" => "GereControleRadio('logement_etage_Etage', 'numetage_label', 'numetage_form, '1');"))
echo $form['reservataire']->render(array("onChange" => "GereControleList('patronal', 'patronal_form', 'this.value');"))
I believe you just have 2 functions with conflicting global scope variable names. Try replacing "GereControleList" with this...
function GereControleList(LabelControle, Controle, val) {
var objLabelControle_ = document.getElementById(LabelControle);
var objControle_ = document.getElementById(Controle);
if (val != '1% Patronal') {
objControle_.style.visibility='hidden';
objLabelControle_.style.visibility='hidden';
}
else {
objControle_.style.visibility='visible';
objLabelControle_.style.visibility='visible';
}
return true;
};
I have found the error : in GereControleRadio, I have deleted a line.
var objControleur = document.getElementById(Controleur);

Categories

Resources