Autocomplete jQuery plugin not working, claiming a variable is undefined [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jQuery variable claiming it's undefined when it has been defined
The problem is that when opening it in firefox and typing a value for input 1 and selecting it, firebug says that the variable phone isn't defined. I tried defining the variables at the start but it still ceased to work.
This is the jQuery:
$(document).ready(function() {
var phone; //fix scoping
var phoneid;
var firmware;
var firmwareid;
$("#input1").autocompleteArray(["iPhone 2G","iPhone 3G","iPhone 3GS","iPhone 4","iPhone 4s"],
{ minChars:1,
matchSubset:1,
onItemSelect:selectPhone,
onFindValue:findPhone,
autoFill:true,
maxItemsToShow:10,
selectFirst:true,
});
$("#input2").autocompleteArray(["1.1","1.2","1.3","1.4","1.5"],
{ minChars:1,
matchSubset:1,
onItemSelect:selectFirmware,
onFindValue:findFirmware,
autoFill:true,
maxItemsToShow:10,
selectFirst:true,
});
function findPhone(li) {
if( li == null ) return alert("No match!");
phone = li.selectPhone;
phoneid = phone.replace("iPhone ","iphone").toLowerCase();
};
function findFirmware(li) {
if( li == null ) return alert("No match!");
firmware = li.selectFirmware;
firmwareid = phone.replace(".","");
$(".info").hide
$(phoneid+firmware).show
};
function selectPhone(li) {
findPhone(li);
}
function selectFirmware(li) {
findFirmware(li);
}
});
And this is the HTML:
<div id="formcontainer">
<input id="input1"/>
<input id="input2"/>
</div>
<div id="iphone2g11" class="info" style="display:none">iPhone 2G</div>
<div id="iphone2g12" class="info" style="display:none">iPhone 3G</div>
<div id="iphone2g13" class="info" style="display:none">iPhone 3GS</div>
<div id="iphone2g14" class="info" style="display:none">iPhone 4</div>
<div id="iphone2g15" class="info" style="display:none">iPhone 4S</div>
I'm using this plugin for autocomplete http://www.pengoworks.com/workshop/jquery/autocomplete.htm

The problem is in your findFirmware() function, change it to
function findFirmware(li) {
if( li == null ) return alert("No match!");
firmware = li.selectFirmware;
firmwareid = phone.replace(".","");
$(".info").hide();
$('#' + phoneid + firmwareid).show(); // This line was messed up
};
There two problems with this line $(phoneid+firmware).show, well four if you count the missing parenthesis and semicolon but...
The div your trying to show has an ID, you don't have # in your selector to select the element by ID
firmware contains the unparsed string with the period so phoneid + firmware becomes iphone2g1.2 when your div ID is iphone2g12 thus you needed to use firmwareid in which you parsed it out of.
Fiddle Demo: http://jsfiddle.net/AaNWM/

Its undefined because you do:
li.selectPhone;
Which .selectPhone doesn't exist on the li element passed in. So, once you get to replacing the string, you get an error.
Assuming that I may, possibly, think, that I might know what you are trying to do, I changed li.selectPhone and li.selectFirmware to li.innerHTML and it works fine. jsFiddle.
Edit: You also were using phone.replace in your firmware function so I changed that as well in the above fiddle.

phone is undefined because li.selectPhone is undefined.
It's hard to guess why that's missing without seeing autoCompleteArray(), which doesn't seem to be part of the jQuery autocomplete plugin, at first glance?

Related

Include IF statement in Javascript

I have written the script below with some help. I am now trying to combine with an IF Statement. Here is what I am trying to accomplish, if %%GLOBAL_Availability%%is empty, then do not display the button. Else, display the button and run the script.
I did some research and came up with the below:
if (%%GLOBAL_Availability%% ==""){
<div><input id="ShopButton" style="display: none";></div>
}
else {
<!--Amazon Shopping button-->
<div><input id="ShopButton" </div>
<script>
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
</script>
}
It did not work at all. I am VB.net, and just learning this hard way.
Any suggestions?
Thanks.
I'm assuming that your variable %%GLOBAL_AVAILABILITY%% is a string since you're testing that it's empty via testing that it's equal to a blank string.
In javascript I'd offer 2 tips for testing if a string exists or is empty.
1 - use the .length property of the String object.
2 - to check that it exists check that the type of %%GLOBAL_AVAILABILITY%% is a string use the identity operator === to check that the variable is of type string.
Your if statement should look like the below:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
//execute code
}
Secondly, javascript is made to manipulate the DOM, so there's no need to insert new HTML based on a condition, you can just manipulate the properties of the existing HTML - in this case, setting the display property of '#ShopButton' to none.This can be achieved like this:
document.getElementById('ShopButton').style.display = "none";
So, your code should look like this:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
document.getElementById('ShopButton').style.display = "none";
} else{
document.getElementById('ShopButton').style.display = ""; //MAKE VISIBLE
document.getQuerySelector('#ShopButton').addEventListener('click', function(){
document.location.href = '%%GLOBAL_AVAILABILITY%%';
});
}
It seems you want the input to be "display: none;" if the variable is empty, in which case you can just change the style attribute based on the variable. Something like:
<div><input id="ShopButton" style="display: none";></div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
This will simply render the element as invisible and then the script will make it visible if the variable isn't empty.
<div>
<input id="ShopButton" style="display: none";>
</div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
Is this what you're trying to do maybe?

Hide a row if value returned is empty

I feel a little stupid asking this question but for some reason I cant for the life of me think on how to do what I want.
I have a <div class="row"> which has my field label and field in it.
I want to completely hide this row if the value of my field is returned as empty.
HTML (Held in my CMS system):
<div id="rollNumber" class="row">
<label class="col-sm-offset-2 col-sm-3 control-label">[!RollNumberLabel]</label>
<div class="col-sm-2 form-control-static">[!RollNumber]</div>
</div>
View code:
if (newBankdetails.RollNumber != null && newBankdetails.RollNumber != "")
{
template.Nvc.Add("[!RollNumberLabel]", "Roll number");
template.Nvc.Add("[!RollNumber]", newBankdetails.RollNumber);
}
I tried doing:
template.Nvc.Add("[!RollNumberLabel]", "");
template.Nvc.Add("[!RollNumber]", "");
but this adds white space between the row above and below this row.
I'm up for any suggestions whether it be JavaScript, JQuery, CSS or if can be done, using HTML (although I don't think it can be done this way).
I can't add any code to my CMS so it needs to be done in my code.
My site is using Twitter Bootstrap
You can test if label text is empty or not.
$(function() {
$(".row").each(function() {
if ($("label", this).text() == "" ) {
$(this).hide();
}
});
});
Working demo: http://jsfiddle.net/m7nytbw4/
I have created an example for you http://jsfiddle.net/gon250/x8m6jLLo/
$(".row").each(function(){
var $row = $(this);
var $childern = $row.children();
if($childern.length > 1) {
if($childern[0].innerText === "" && $childern[1].innerText === "") {
$row.hide();
}
}
});
basically what I'm doing is check all the children of the rows and if both are empty hide the row.
Hope it's helps!
Use CSS display style property to hide the row.
$("#rollNumber").css("display", "none");
I am not sure if this is a overkill solution for your problem, but with jQuery and regex you could do something like this:
$('.row').each(function(){
var row = $(this);
if(! /^[a-zA-Z0-9]+$/.test(row.find('label'))){
// No alphabetical characters found
row.css('display','none');
}
});

Uncaught TypeError: Cannot set property 'display' of undefined

I am in the process of migrating an existing platform to a new server. I am taking the opportunity to upgrade PHP ect and standardise/debug the code as the previous maintainers have had different standards.
I have opted for PHP version 5.4.33 for now, once I have managed to move everything over to mysqli I will look to go to a more recent version. I didnt think anything server side would make a difference to AJAX/JS? As far as I am aware is it not client side?
Since I have moved the code over I am having issues with AJAX/JS. I am not the greatest at AJAX/JS and could use some assistance please. Even though every submit works differently through the entire platform I do not want to remove the AJAX/JS that already exists. I will most likely use it as an opportunity to how to use it as it makes end user experience smoother.
Using Chrome to debug I am receiving the following error on clicking the Save button:
Uncaught TypeError: Cannot set property 'display' of undefined
email_user
onclick
This is the Save button code
<span id="loading" style="color: red; font-size: x-small; display: none; text-decoration: blink;">Loading... Please wait..</span><input type="button" value="Save" class="save" onclick="if(validate()){ email_user(); }" />
This is the function code for validate()
function validate() {
var errorString = "";
if(isBlank(document.getElementById("forename").value)) {
errorString += " - Please input a forename\n";
}
if(isBlank(document.getElementById("surname").value)) {
errorString += " - Please input a surname\n";
}
if(isBlank(document.getElementById("company_name").value)) {
errorString += " - Please select a company\n";
}
if(document.getElementById("username").value != "" || document.getElementById("password").value != "") {
if(isBlank(document.getElementById("username").value)) {
errorString += " - Please input a username\n";
}
if(isBlank(document.getElementById("password").value)) {
errorString += " - Please select a password\n";
}
}
//if not a solicitor then cases mandatory
if(document.getElementById("company_role_type_id").value == 2) {
if(document.getElementById("other_view_if").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(document.getElementById("company_role_type_id").value == 3) {
if(document.getElementById("other_view_ea").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(errorString) {
alert('Please correct the following items:-\n\n'+ errorString);
return false;
}
else {
return true;
}
}
This is the function code for email_user()
function email_user(){
if(skip_email == true){ $('user').submit(); }
var url = 'email_user.php';
var params = '?' + $('user').serialize() + '&from_edit=1';
$('loading').style.display = 'inline';
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: params,
onComplete: show_response
});
function show_response(this_request){
//alert(this_request.responseText);
var reply = this_request.responseText.evalJSON(true);
if(reply['status'] == false){ var blah = ''; }
else{ alert(reply['message']); }
//$('loading').style.display = 'none';
$('user').submit();
}
}
Thinking about it, maybe it is more to do with the Apache version?? Just in case Apache version is 2.2.15.
Any assistance you guys can give me will be greatly appreciated! If you need any more information please let me know.
Kind Regards,
n00bstacker
As previously stated in comments, your code has some issues, your line (the one that is triggering the error, can be optimized in the following way:
$('#loading').css("display","inline"); //Selector is ok now...
In the other hand, I also noticed that you have a second selector $('user') that won´t work. Remember that anything without a dot, or a sharp will be considered as an element selector (loading, and user elements, won´t exist in your document unless you created it.
Remember:
$("#myId") //id selector
$(".myClass") //class selector
If "user" is the form name, the code may work. Remember that you want to catch the form submit event.
Regards,
Guillermo
Try changing $('loading') to $('#loading')?

How to validate javascript "not null" for ajax return values [duplicate]

This question already has answers here:
Making sure at least one checkbox is checked
(10 answers)
Closed 9 years ago.
My Php form (organisation.php) has this javascript validation
if(document.orgform.startdate.value == '')
{
alert('Enter Start Date');
document.orgform.startdate.focus();
return false;
}
if(document.orgform.enddate.value == '')
{
alert('Enter End Date');
document.orgform.enddate.focus();
return false;
} //these work fine
JQUERY
function getorgname(key)
{
var orgvalue = key.value;
$.ajax({
type:"POST",
url:"searchorg.php",
data:{orgname : orgvalue},
success: function(res) {
$('#org').html(res);
}
});
} //returns organisation names with checkboxes, working fine
HTML Part of organisation part is as follows:
<input type="text" name="startdate" id="sdate" >
<input type="text" name="enddate" id="edate">
<div id="organisation></div> //ajax returned values displayed here, working fine.
Now how do I test if at least one checkbox is checked?
I tried putting validation in ajaxorganisation.php as well as orgnaisation.php and called that function while submitting organisation.php, but it does not work.
Server side validation is working fine, but would appreciate if there is a way for client side validation too
A. Fix your html code. The containing div id attribute is missing the ending double quote delimiter.
B. whenever you wish to check if at least one is clicked, call the following function with an argument of '#organisation'
function at_least_one_checked(container) {
var $c_list = $(container + ' input[type="checkbox"]');
for (var i = 0; i < $c_list.length; ++i)
if ($($c_list[i]).prop('checked'))
return true;
return false;
}
Better you should create a group of these checkboxes by keeping same name for them. Like in future if you've added more input element, it will not affect the code.
try something like this
// chkbx class on checkbpx element
var flag = false
jQuery('.chkbx').each(function(){
if(this.checked){
flag = true;
}
})
return flag;// true if checked else false

How to get value of textbox on page load, if it is null? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
Want to check first that, Is text box contains nothing on page load ?
Then assign some value to it.
if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}
But getting error
"JavaScript runtime error: Unable to set property 'value' of undefined or null reference"
How to do this?
It is because your DOM is not ready so wait until load complete:
window.onload=function(){
if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}
};
You're probably trying to access the element before you defined in page, so you should execute that code on window.load event or move that code just before </body>
as alternative you may use the placeholder attribute supported on many modern browsers
<input type="text" id="txtBoxId" placeholder="Some text here" />
If the input has no value, the placeholder value will be shown instead
(polyfills of this behaviour are available for older browser)
You are trying to access the property 'value' on a null (or undefined) object, wich cause an exception, assuming your ID may not be txtBoxID
It is not safe to test null for the textbox value. You should use empty string instead.
I created a jsFiddle which shows this:
<input type="text" id="txtBx" />
document.getElementById("txtBx").value = null;
alert("test 1 textbox is null \n" + (document.getElementById("txtBx").value == null));
alert("test 2 textbox is empty string \n" + (document.getElementById("txtBx").value == ""));
http://jsfiddle.net/kZhHa/3/
(I'm using Chrome)
Are you doing your code above after the page is loaded?
window.onload = function() {
if (document.getElementById("txtBoxID").value == null) {
document.getElementById("txtBoxID").value = "Some text here";
}
}
Note that window.onload isn't best way to check whether page is loaded. It depends on the browser's spec. See window.addEventListener or window.attachEvent or IE.
Please try the below code, you need to set the value to the null first in the line
Name: <input type="text" id="myText" value=''>
Here is the demo :
function func() {
if (document.getElementById("myText").value == '') {
document.getElementById("myText").value = "Some text here";
} else {
alert("not null");
}
}
Name: <input type="text" id="myText" value="">
<p>Click the button to change the value of the text field.</p>
<input type="button" id="button" value="Click Me" onClick="func();" />
If you have JQuery available here is another way of accomplishing what you are asking for. In the document.ready function you can get the value of your text using the id of your textbox and wrapping it in JQuery. This will allow you to check and replace the value of your text box in the case that it is empty by using the .val() function
$(document).ready(function () {
if($('#id-of-your-textbox').val() == ' ')
{
$('#id-of-your-textbox').val('some text');
}
});

Categories

Resources