Pass Value of Input Automatically With Javascript - javascript

I was working on passing a value that is put into a text input box, to another text input box as the user types.
I got everything to work on jsfiddle but for some reason I can't get it to work if I use it anywhere else. Im using pure javascript, not jquery.
So, here is my html code
<input id="imput1" type="text" class="firstbox">
<p>Box to Retrieve The Input</p>
<br />
<input id="gift_card_recipient" type="text" class="replica" value="box1" />
<input type="text" class="replica2" value="box2" />
And the Javascript that I am using to pass the value as the user types, from the first box, to the second box:
(function() {
var var1 = document.getElementById('imput1'),
var2 = document.getElementById('gift_card_recipient'),
callback = function () {
var2.value = this.value;
};
if (var1.addEventListener) {
var1.addEventListener('keyup', callback);
} else {
var1.attachEvent('onkeyup', callback);
}
}());
Again, I got this to work on jsfiddle, and here is a demo of what it looks like, but for some reason, if I use it on my pc on a html file, or on my server, it wont work.
I am linking the js file in the header, and also inspected it in chrome. here is the error I got from chrome:
Uncaught TypeError: Cannot read property 'addEventListener' of null
Not really sure why its throwing that. but here is my jsfiddle that I have that actually works. but doesn't on the server or my pc: http://jsfiddle.net/C3SPM/

Include your script block at the end of the body (or after the elements in question). Or wrap your code in an onload/onDomReady handler.
The specific error you are getting is because your code is running before the elements in question have been parsed, which means that document.getElementById('imput1') returns null because it can't find the element. The reason it works in a fiddle is that by default jsfiddle wraps any JS in an onload handler, so then when the code runs the elements have been parsed (you can change this setting in jsfiddle using the drop-down on the left under "Frameworks & Extensions").

Related

document.getElementById("numbern").value causes Uncaught TypeError: Cannot read property 'value' of undefined

I'm trying to get value from the input box. The id is correct and input is shown.
In console it shows an
UncaughtTypeError Uncaught TypeError: Cannot read property 'value' of undefined and links to line 41 but all is correct as I think.
HTML
<input id="numbern" name="nub" placeholder="Your Roll No." class="form-control col-6" autocomplete="off">
Javascript
docsd=document.getElementById('numbern');
console.log(docsd.value);
Can I know what I'm doing wrong?
Make sure that the element exists in DOM before you call your selector. document.ready can be used to wait for the document object to load first. Following snippet works fine:
function getValue() {
docsd = document.getElementById('numbern');
console.log(docsd.value);
};
document.addEventListener('DOMContentLoaded', getValue(), false);
<input id="numbern" name="nub" placeholder="Your Roll No." class="form-control col-6" value="10" autocomplete="off">
Use this Code it will listen to event after you change the value in input box it will execute the console.log
`let docsd=document.getElementById('numbern');
docsd.addEventListener("input",()=>{
console.log(docsd.value);
})`
Because my reputation doesn’t allow me to comment, I have to say it here. I have encountered the similar situation when I try to use jquery to manually add an element to the DOM. So as #CBroe suggested, please find out when your js is executed and the element is definitely not there.
You can use F12 button to open the google console to check whether element is there:
Hope it helps you to find your way out. I can't find any problem in this code snippet so it is more likely related to how you render your html and its happening time compared to the js execution time.
-----update-------
Based on your code in fiddle, you should definitely move the script down like behind the DOM body
---------Test---------
As you can see, I have tested on my google browser and it works. I can get the element and manipulate it and there is not error after I comment the getElementById("numbern") in the top script.

How is this Uncaught TypeError: occurring?

I recently saved my questionnaire as a PHP file to include a validation script and am coming up with the error
Uncaught TypeError: Cannot set property 'onClick' of null
It's also pointing me to line 163 of my javascript file which is the function for the "next" button on the first page.
The most common reason I've seen so far in everything I've been reading is that it's triggering before the element loads in the page. In response to this I linked the .js file in the bottom of the body tag but it still gives me the same error.
The buttons on the HTML file I saved as a PHP still works fine with no problems. Here's how I have everything coded.
//the function for the page change buttons//
window.onload=function(){
//a bunch of variables come prior to this//
var start = document.getElementById("start_btn");
var p1a = document.getElementById("p1_next");
var p2a = document.getElementById("p2_back");
var p2b = document.getElementById("p2_next");
//more variables continued//
start.onclick=function(){ //coded exactly the same as where the error occurs//
welc_p.style.display="none";
page01.style.display="block";
window.location="#page01";
};
p1a.onclick=function(){ //line 163 where the error occurs//
page01.style.display="none";
page02.style.display="block";
window.location="#page02";
};
p2a.onclick=function(){
page01.style.display="block";
page02.style.display="none";
window.location="#page01";
};
p2b.onclick=function(){
page02.style.display="none";
page03.style.display="block";
window.location="#page03";
};
//more functions continued//
}
The HTML I'm using as the button
<div class="button" id="p1_next" style="width:22%; height:40px; margin:auto;">
<div class="sub_title02">Next</div>
</div>
I added a little extra just so you guys can see the flow of things and what's around the part that's giving an error. I also went back and forth adding and "onclick" function to the buttons but that still didn't work. Does anybody have any clue what's going wrong here?
The short and easy answer is, your selector doesn't find the specified element. Can you show the code including your html?
Either you misspelled the ID of the element you are trying to add the click event to, or as you proposed yourself the html is not loaded yet when you are executing your javascript.
Ok I stumbled upon what was causing the problem. From looking at the coding over and over so much I realized I forgot to give the textarea input a name like all the other inputs so I gave it one and continued scanning the code, eventually I uploaded it and noticed the problem was gone. Just to be sure on what it was I deleted the name and tested it and the problem came back.
so I guess if a textarea in a PHP file doesn't have a name attribute it for some reason makes itself a self closing tag that gets ignored by the browser until it runs into the closing tag of another textarea WITH a name attribute. So that's what caused the javascript to throw back the null error because the trigger element didn't exist because it was eaten by the textarea.... so there was nothing there when the javascript looked for it. Thanks for taking the time to help me figure it out. :)

JQUERY: ID not found, just defined before

I've got a problem I don't understand.
I want to create a datepicker with JQUERY (UI-1.9.1 + JQ 1.8.2)
I define the
<input id="date1" .... value="">
DateSelClickHere
"DateSelClickHere" should be a picture later on.
If you now click to the empty datefield, it just works fine.
If you click to the text (or image),I get this: [object Object]
Sample here:
http://jsfiddle.net/3DH3L/
I don't get it?!?
PS: I will try it with the property "image" - but - this is the crap - it's not my code and I just start with this project, so I first search for the "easy way" to fix the errors.
The problem is that you are using a JavaScript URIs. The purpose of these is to generate a document to display by running some JavaScript.
If you just want to run some JS, then use a button. Use a link only if you want to link somewhere.
<input type="button" value="DateSelKlickHere">
You could use an onclick attribute, but you'd be better off binding your JS with JavaScript.
$('#date1 + input[type="button"]').on("click", function (evt) {
$('#date1').focus();
});

Get usercontrol property value using Javascript

I have a user control named lets say ucName that has a property named InitialValue.
Everything's fine , Im rendering the control and setting the initial value.
In my aspx page, Im doing like this:
<td>
<tagprefixName:ucName ID="Editor" runat="server" InitialValue="bla bla"/>
</td>
I have a button that will post back the page, but before post backing, im doing:
<asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveRes" OnClientClick="SaveValue()" />.
In javascript function I want to get the value of the initial value of my user control:
I tried many solutions, but they are either returning null or undefined.
function SaveValue() {
var v= $("[id$=Editor]").attr("InitialValue");
var v = $("#Editor").attr("InitialValue");
var v= $("input[id$=Editor]").attr("InitialValue");
var v= $("span[id$=Editor]").attr("InitialValue");//since the uc is rendered as span
}
How can I get the InitalValue of my uc ??
Thanks alot
EDIT
This is my html:
<span id="ctl00_PlaceHolderMain_Editor"><input name="ctl00$PlaceHolderMain$2f1445d6-b13d-4f8f-9497-9c14e5d2b076" type="text" value="fgerf" id="ctl00_PlaceHolderMain_2f1445d6-b13d-4f8f-9497-9c14e5d2b076" /></span>
NB: I tried using .val() .value() but still getting an empty
I'm presuming that the markup gets parsed on the server, and the resulting HTML code does not have this InitialValue property. Try viewing source to see what the actual code is and then paste it into the question.
If all the control does is set the contents of a span, then the following should work:
$("span#Editor").text();
you could retrieve it in the aspx markup page using an expression like this
var initialValue = <%= Editor.InitialValue %>;
The uc is rendered as an input inside a span has the uc's id, so the javascript code will be:
$("span[id$=Editor] input[type=text]").val();
Edit: updated to use object names now that you've included the actual HTML in your page. The only thing I'm still unsure of is whether ctl00_PlaceHolderMain_Editor is the same every time or not. If it's not the same every time, then you need to find a way (server-side) to assign an id that is constant so you have a reliable way to reference the object in the web page.
Adding this code will "save" the initial value to an attribute of the editor object when the page is first loaded.
$(document).ready(function(){
var $editor = $("ctl00_PlaceHolderMain_Editor input");
$editor.attr("data-initialValue", $editor.value());
});
And, then you can read back the initial value anytime later with this code:
$("ctl00_PlaceHolderMain_Editor input").attr("data-initialValue");
If, for any reason this code isn't working, then (in the ready handler), you need to find out whether it's not working because $("ctl00_PlaceHolderMain_Editor input") isn't being found or whether it's because it isn't able to save the data value on the object.

javascript not getting value of input box

I seem to be having trouble with passing the value of an input box to anything else in my javascript.
It's not producing any errors - and I remember reading somewhere that you can have issues if the document hasn't finished loading - but I'm pretty sure it has!
The code in question is as follows in the javascript:
var address = getElementById(addyInput).value;
document.getElementById('add').innerHTML = address;
And in the HTML
<form>
<input name="addyInput" placeholder="Don't forget postcode!">
</form>
<button id="start" onclick="initialize()">Start!</button>
<p>Address Test
<div id="add"></div>
</p>
I know that the button itself is working as it fires the rest of my code fine without the offending code - however the moment I uncomment that little block at the top, it just does nothing. (no errors etc)
Any help on that one would be hot! Thanks :)
Update:
I now have it working! Thanks muchly for all the help!!
Your form needs to look like this (add an id attribute):
<form>
<input id="addyInput" name="addyInput" placeholder="Don't forget postcode!">
</form>
And the first line of Javascript needs to look like this (since getElementById is expecting an ID rather than a name).
var address = getElementById('addyInput').value;
Additionally, getElementById expects the id argument to be a string (hence the quotes). If you pass it addyInput without quotes, it'll try to interpret addyInput as a variable which has a value of undefined and you won't get back the DOM element you want.
Or, if you were using jQuery, you could leave the form markup as-is and change the Javascript to this:
var address = $('input[name=addyInput]').val();
Make sure to specify and id on the input. You only have a name.
You need to add the id "addyInput" to your form input rather than just the name.
getElementById expects a string.
var address = getElementById('addyInput').value;
If you put this directly into a script section in the head, then you will have a problem because the page is not loaded completely but the code is executed already.
And of course you should define an id for the input element as the others already said.
what you are getting is an array, you need to fetch your array into some readable data. Try something like:
$value = array_shift( $yourarray );
or if it's a multi value array you can just loop it to fetch out the values.

Categories