Using JavaScript with form data - javascript

I am attempting to simply pull an input from an html form and manipulate it with JavaScript. When I console.log the variable I created in JavaScript I am just getting my html element back. If I attempt to add [0] or .value, I get undefined and a JQuery error, respectively. I am at a loss as to the reason this isn't working. If it matters I am doing all this in CodePen.
HTML:
<div>
<form id="myForm">
Construction Year: <br>
<input type="text" id="construction_field" name="construction_field" value=""><br>
</form>
<button onclick="myFunction">Find P</button>
<p id="demo"></p>
</div>
JavaScript:
$(document).ready(function(){
function myFunction () {
var constructionYear = document.getElementById("construction_field");
console.log(constructionYear);
}
});
I apologize for such a simple question, but I can't find an answer that works to save my life. If it isn't obvious I am very new and struggling, any examples would be amazing.

If you wish to use jQuery:
var constructionYear = jQuery('#construction_field').val();
If you wish to use vanilla JavaScript:
var constructionYear = document.getElementById('construction_field').value;

Just use console.log(constructionYear.value);

Related

Get current value of search input on SharePoint

Would like to get a pure Javascript solution for my situation.
My HTML and JS is as follows. But the HTML can't be manipulated unfortunately as its on SP.
function getCurrentValue() {
var searchQuery = document.getElementById("SearchBox").children[0].children[0].value;
console.log(searchQuery);
}
<div id="SearchBox">
<div id"randomGeneratedId">
<input type="text" value="Search..." id="anotherRandomGeneratedId"/>
</div>
</div>
<br/>
<input type="button" value="Run!" onClick="getCurrentValue();">
The JS above works in the snippet here but on my page it returns the default value of the input ie. "Search..."
FYI its running on SharePoint 2013. I should note that I managed to get it to work when getElementId("anotherRandomGeneratedId") but that require writing a custom script for every page.
Have a try to modify getCurrentValue() to:
function getCurrentValue() {
var searchQuery = document.querySelector("#SearchBox input").value;
console.log(searchQuery);
}

Scan QR Code value into an input field

This is the scanner I am using...
On Web : https://atandrastoth.co.uk/main/pages/plugins/webcodecamjs/
On Git : https://github.com/andrastoth/WebCodeCamJS
It's working 100%. But I need to add some custom extra's.
When the QR Code is scanned it outputs my result into this paragraph tag.
<p id="scanned-QR"> The scanned code text value is printed out here </p>
However I need it to be an input field so I can use it's value in a url.
How can I set an input field equal to the value submitted to the Paragraph tag?
I have tried these methods and they failed :
Method 1
<input id="scanned-QR"> The scanned code text value is printed out here </input>
Method 2
<p id="scanned-QR" onchange="update"></p>
<input id="code_id_value" type="text" name="" value="">
<br>
<script>
function update(){
var code_id_value = document.getElementById("scanned-QR").innertext;
document.getElementById("code_id_value").value = code_id_value;
}
</script>
The key that you're missing is that the T in .innertext needs to be capitalised (as .innerText).
In addition to this, using inline event handlers is bad practice, and you should consider using .addEventListener() instead of onchange.
This can be seen working in the following:
document.getElementById("scanned-QR").addEventListener("click", update);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerText;
document.getElementById("code_id_value").value = code_id_value;
}
// Demo
update();
<p id="scanned-QR">Text</p>
<input id="code_id_value" type="text" name="" value="">
Hope this helps! :)
So this is the solution I came up with.
Here's my paragraph and input function
<p id="scanned-QR" onchange="update">SCAN.BZ</p>
<input id="code_id_value" type="text" name="" value="">
Here's my function. WITH a interval for every millisecond or faster "I think it's every millisecond".
It runs smoothly and doesn't lag. and the result is practically immediate.
<script type="text/javascript">
setInterval(update,1);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerHTML;
document.getElementById("code_id_value").value = code_id_value;
}
update();
</script>
Thanks for the help "Obsidian Age" Really appreciate it. :)

storing and loading input data in localStorage step by step

I am trying to use localStorage to store some input data.This is what I came up with and no it does not work.Can someone explain to me how I can get this to work? I have searched for tutorials but I find it hard to understand how to store and retrieve the data from the localStorage.This is my script:
<body onLoad="get();">
<article id="hldr">
<input type="text" id="kID" class="regTXTBOX" placeholder="office ID">
<input type="text" id="gID" class="regTXTBOX" placeholder="user ID">
<button id="save" onClick="store();" style="margin-bottom:20px;">save data</button>
<button id="login" onClick="store();">log-in</button>
</article>
<span id="1"></span>
<span id="2"></span>
</p>
<script type="text/javascript">
function store(){
var kid = document.getElementById("kID");
localStorage.setItem("kidStore", kid.value);
}
function get(){
var one = document.getElementById('1').value
one = localStorage.getItem("kidStore");
}
</script>
</body>
I want it to fire when the page loads, although I probably don't even need the onLoad function for that.
I also don't really need the button to save the data but I just put it in for testing.
If someone can provide me a step-by-step explanation to get this to work I would be very happy.
Your problem is that the span element does not have a value property. So changing it to innerText will make it work (along with the assigning problem which I mentioned in the comments).
The following will work:
document.getElementById('1').innerText = localStorage.getItem("kidStore");
Working fiddle: http://jsfiddle.net/k6r53/

How can I use querySelector on to pick an input element by name?

I recently received help on this site towards using querySelector on a form input such as select but as soon as I took <select> out it completely changed what had to be done in the function.
HTML:
<form onsubmit="return checkForm()">
Password: <input type="text" name="pwd">
<input type="submit" value="Submit">
</form>
Javascript:
<script language="Javascript" type="text/javascript">
debugger;
function checkForm() {
var form = document.forms[0];
var selectElement = form.querySelector('');
var selectedValue = selectElement.value;
alert(selectedValue);
</script>
Before, I had ('select') for the querySelector, but now I'm unsure what to put there.
I've tried multiple things as well as querySelectorAll but I can't seem to figure it out.
To be clear I'm trying to pull the name="pwd".
How could I do this?
You can try 'input[name="pwd"]':
function checkForm(){
var form = document.forms[0];
var selectElement = form.querySelector('input[name="pwd"]');
var selectedValue = selectElement.value;
}
take a look a this http://jsfiddle.net/2ZL4G/1/
I know this is old, but I recently faced the same issue and I managed to pick the element by accessing only the attribute like this: document.querySelector('[name="your-selector-name-here"]');
Just in case anyone would ever need this :)
1- you need to close the block of the function with '}', which is missing.
2- the argument of querySelector may not be an empty string '' or ' '... Use '*' for all.
3- those arguments will return the needed value:
querySelector('*')
querySelector('input')
querySelector('input[name="pwd"]')
querySelector('[name="pwd"]')
Note: if the name includes [ or ] itself, add two backslashes in front of it, like:
<input name="array[child]" ...
document.querySelector("[name=array\\[child\\]]");
So ... you need to change some things in your code
<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>
<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;
function checkForm() {
alert(pwd.value);
}
</script>
Try this way.
I understand this is an old thread. However, for people who stepped upon this like me, you may utilize the following code.
select the input using elements collection
form.elements['pwd']
or using namedItem method under elements collection
form.elements.namedItem('pwd')
These examples seem a bit inefficient. Try this if you want to act upon the value:
<input id="cta" type="email" placeholder="Enter Email...">
<button onclick="return joinMailingList()">Join</button>
<script>
const joinMailingList = () => {
const email = document.querySelector('#cta').value
console.log(email)
}
</script>
You will encounter issue if you use this keyword with fat arrow (=>). If you need to do that, go old school:
<script>
function joinMailingList() {
const email = document.querySelector('#cta').value
console.log(email)
}
</script>
If you are working with password inputs, you should use type="password" so it will display ****** while the user is typing, and it is also more semantic.
querySelector() matched the id in document. You must write id of password in .html
Then pass it to querySelector() with #symbol & .value property.
Example:
let myVal = document.querySelector('#pwd').value
form.elements.name gives better perfomance than querySelector because querySelector have to look for in entire document every time. In case with form.elements.name computer directly gets inputs from form.

How can I escape a DOM name in javascript?

I have a form element that I want to address via javascript, but it doesn't like the syntax.
<form name="mycache">
<input type="hidden" name="cache[m][2]">
<!-- ... -->
</form>
I want to be able to say:
document.mycache.cache[m][2]
but obviously I need to indicate that cache[m][2] is the whole name, and not an array reference to cache. Can it be done?
UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.
Here's some code that proves it:
<html>
<body>
<form id="form1">
<input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/>
<input type='button' value='Test' onclick='showtest();'/>
<script type="text/javascript">
function showtest() {
var value = document.getElementById("field[m][2]").value;
alert(value);
}
</script>
</form>
</body>
</html>
Update: You can also use the following to get the value from the form element:
var value = document.forms.form1["field[m][2]"].value;
Use document.getElementsByName("input_name") instead. Cross platform too. Win.
Is it possible to add an id reference to the form element and use document.getElementById?
-- and in the old days (in HTML3.2/4.01 transitional/XHTML1.0 transitional DOM-binding) you could use:
form.elements["cache[m][2]"]
-- but the elements-stuff is, as Chris Pietschmann showed, not necessary as these binding-schemes also allow direct access (though I personally would prefer the extra readability !-)

Categories

Resources