getElementByName validation - javascript

I know how to get fields to validate with JavaScript using methods such as getElementById etc. For this instance I need to use the getElementByName method. I have the error 'Cannot read property 'nodeValue' of null in console.log.
Here is code that I used with the getElementByName method which worked
HTML
<button name="button1">Hello</button>
<div class="form-row">
<div class="field w100">
<label for="primary_phone">Primary phone (digits only) *</label>
<input type="text" name="primary_phone" id="primary_phone" placeholder="hello"></input>
</div>
</div>
<div class="form-row">
<label for="confirm_phone">Confirm phone (digits only) *</label>
<input type="text" name="confirm_phone" id="confirm_phone"></input>
</div>
</div>
JavaScript
var btn1 = document.getElementsByName('button1')[0];
var btn1Text = btn1.firstChild.nodeValue;
console.log(btn1Text);
Below is the code that is returning the error.
HTML
<button id="button">Button</button>
JavaScript
function validate() {
var primaryNo = document.getElementsByName('primary_phone')[0];
var confirmNo = document.getElementsByName('confirm_phone')[0];
var primaryValue = primaryNo.firstChild.nodeValue;
var confirmValue = confirmNo.firstChild.nodeValue;
if (primaryValue !== confirmValue) {
alert('Numbers do not match');
} else {
alert('congratulations')
}
};
var btn = document.getElementById('button');
btn.addEventListener('click', validate, false);
Any ideas?

Looks like you might be having input fields whose value you are trying to fetch.
In that case, they don't have any child elements, instead you need to get their value like
var primaryValue = primaryNo.value;
var confirmValue = confirmNo.value;

What is the result of
var btn1 = document.getElementsByName('button1')[0];
in console (console.log(btn1);) ?
Be careful with tag names: button, button1... maybe you have a syntax mistake.

Related

how to button on click takes all the content from textarea, runs a function and then displays the final value inside new div?

I'm in the learning stages, can you please give me the answer with the explanation.
Also if possible, I would appreciate it if you could explain to me what I have done wrong here and then also show me the better way of doing it.
//ARROW FUNCTION
const reverseNumber = num => (num.toString().split("").reverse().join(""));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#output-button');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
textAreaValue = reverseNumber(textAreaEl)
outputAreaEl.innerHTML = textAreaValue.value;
});
<form action="">
<label for="object" title="object">JavaScript function that returns a passed string with letters in alphabetical order</label>
<textarea id="text-area" name="object-name" id="" cols="30" rows="5"></textarea>
<input type="button" value="RETURN" id="return-value" />
<div id="output"></div>
</form>
First of all, there is no element with #output-button. You need to fix that.
You are passing the element itself to the reverseNumber(), you should pass the value to function.
I will also suggest you use innerText or textContent instead of innerHTML if the text is plain text (not htmlString).
Demo:
const reverseNumber = num => (num.toString().split("").reverse().join(""));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#output-button');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
textAreaValue = reverseNumber(textAreaEl.value); //pass value here
outputAreaEl.textContent = textAreaValue; //no need to use value here
});
<form action="">
<label for="object" title="object">JavaScript function that returns a passed string with letters in alphabetical order</label>
<textarea id="text-area" name="object-name" id="" cols="30" rows="5"></textarea>
<input type="button" value="RETURN" id="output-button"/> <!--fix the id here-->
<div id="output"></div>
</form>
Your script should be like this
const reverseNumber = num => (num.toString().split("").reverse().join(""));
console.log(reverseNumber(54321));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#return-value');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
let textAreaValue = reverseNumber(textAreaEl.value);
outputAreaEl.innerHTML = textAreaValue;
});
First, your document.querySelector('#output-button') is not match with <input type="button" value="RETURN" id="return-value"/>.
Second, you have to use variable declaration keyword to get textAreaEl.value
First of all textarea id is incorrect so querySelector is returning undefined and click event is not attached. I have corrected the button id in html.
You need to use textAreaEl.value to find the textarea text and pass it to reverseNumber function.
//ARROW FUNCTION
const reverseNumber = num => (num.toString().split("").reverse().join(""));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#output-button');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
textAreaValue = reverseNumber(textAreaEl.value)
outputAreaEl.innerHTML=textAreaValue;
});
<form action="">
<label for="object" title="object">JavaScript function that reverses a number</label>
<textarea id="text-area" name="object-name" id="" cols="30" rows="5"></textarea>
<input type="button" value="RETURN" id="output-button"/>
<div id="output"></div>
</form>

JavaScript putting two variable's value into an array

i have two variables name and location which are provided by two <input type="text">. I need to get an outcome of Smith_California but I am getting an output of userName_userLoca in the console.
Any suggestions would help.
currently, I have:
HTML:
<form class="inputContainer" id="inputContainer" methed="post">
<label for="userNam">Your Name</label>
<input type="text" class="userNam" id="userNam" name="userNam" />
<label for="userLoca">Your Location</label>
<input type="text" class="userLoca" id="userLoca" name="userLoca" />
<button class="vButton" id="vButton" type="submit" onclick="testfun()">
Begin Test
</button>
</form>
Javascript:
var userName = document.getElementById('userNam');
var userLoca = document.getElementById('userLoca');
var userSID = ['userName', 'userLoca'];
console.log(userSID.join('_'));
Remove the quotes and use .value:
var userSID = [userName.value, userLoca.value];
You are accessing dom-element, using var userName = document.getElementById('userNam');.
Try with var userName = document.getElementById('userNam').value.
Also remove the quotes from var userSID = ['userName', 'userLoca']; and use it like below
var userSID = [userName, userLoca];

get an element id and then use it in a getElmentByID to trigger a function on click

function getId(e){
var xid = e.target.id;
console.log(xid);
}
<form onclick="getId(event)">
<label for="name" id="I am an Span">Nombre</label><br>
<input type="text" name="name" id="tbx_nombre"> <br>
<span id="nombre"></span> <br>
</form>
<div id="result"></div>
When the user click on a texbox the function gets the id of the element, then the deleteSpan method is call with the splitted id of the textbox which is now the id of the span to be changed to an emply string.
I get this error Cannot set property 'onclick' of null at getId
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name"></span>
...MORE INPUTS AND SPAN TAGS...
</form>
JS
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
document.getElementById(xid).onclick = function(){deleteSpan(spanId)};
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
You are getting that error because when you try to set the click handler on the span by ID, you don't currently have the correct ID. It's null, because the click target is currently the form (which doesn't have an ID) instead of the input.
As others mentioned, the click event listener should be attached to the input.
But you also don't need to set a separate click handler within getId--you can just call deleteSpan in the getId function. In fact, if you set it inside another handler like you have, it won't work the first time (unless that's your desired outcome).
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form>
<input onclick="getId(event)" type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>
onclick attribute event handler should be at input instead of form
<form>
<input type="text" name="name" id="tbx_name" onclick="getId(event)"><br>
<span id="name"></span>
</form>
or even better, use addEventListener for the inputs which have id format as tbx_{{value}}
var allInputs = document.querySelectorAll("input[id^='tbx_']");
allInputs.forEach( s => s.addEventListener( "click", e => getId ));
You can invoke above code when the form has loaded (at document load or window load).
You have to set the attribute onclick in input instead of form to get the expected id. Otherwise you have to check if the target node is INPUT or not:
function getId(e){
if(e.target.nodeName == 'INPUT'){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>

Textfields not passing values properly

I'm willing to use two textfields to pass on values via url.
Here are my textfields:
<h3 class="title1">Email</h3>
<input type="text" id="myTextField1" />
<br/><br/>
<h3 class="title2">Secret</h3>
<input type="text" id="myTextField2" />
<br/><br/>
There's a link below them:
<a id="myLink" href="index2.php"></a>
Then there's a function I use, which should create something like:
index2.php?email=value1&secret=value2
However what I am getting is:
index2.php?email=value1, secret=value1&email=value2, secret=value2
This is the function I use:
document.querySelector('#myBtn').addEventListener('click', function change() {
function isInvalid(input) {
return input.value.length == 0;
}
var inputs = [...document.querySelectorAll('[id^="myTextField"]')];
var anchor = document.getElementById('myLink');
var querystring = inputs.map((input) => {
// Remove all leading non-digits to get the number //ex bladiebla1 = 1
var number = input.id.replace( /^\D+/g, '');
var titles = [...document.querySelectorAll('.title'+ number)];
titles.forEach((title) => title.innerHTML = input.value);
return `email=${input.value}`+` secret=${input.value}`;
});
anchor.href = `index2.php?${querystring.join('&')}`;
document.getElementById('result').innerHTML = querystring;
});
I realize that it is wrong and I get why this doesn't return what I want however I do not know how to fix this..
Could anybody tweek my code and point me in the right direction?
You're overcomplicating things here a bit.
You have the inputs in the inputs variable. If they had a name attribute in the html you can simply map over them and get the values out.
You don't really need the bit where you parse the number from the ID.
document.querySelector('#myBtn').addEventListener('click', function change() {
function isInvalid(input) {
return input.value.length == 0;
}
var inputs = [...document.querySelectorAll('[id^="myTextField"]')];
var anchor = document.getElementById('myLink');
var querystring = inputs.map((input) => {
return `${input.name}=${input.value}`;
});
anchor.href = `index2.php?${querystring.join('&')}`;
document.getElementById('result').innerHTML = querystring.join('&');
});
<h3 class="title1">Email</h3>
<input type="text" name="email" id="myTextField1" />
<br/><br/>
<h3 class="title2">Secret</h3>
<input type="text" name="secret" id="myTextField2" />
<br/><br/>
<button id=myBtn>Run the function</button>
<a id=myLink>Target Link</a>
<h3>Results:</h3>
<div id=result></div>
You iterate through each input and set email and secret for each of two inputs. Just add check for id. Something like return number === 1 ? email=${input.value} : &secret=${input.value};

Jquery update ckfinder form field

I'm trying to update an input field value .ckfinder-input via ck finders pop up image selector.
It all works fine until I try and assign the selected image URL to the input field input.val() = fileUrl and get the following error message:
ReferenceError: invalid assignment left-hand side
Could someone shed some light on what I'm doing wrong?
My code is as follows:
$(".ckfinder-modal-button").on("click", function() {
input = $(this).parent().find(".ckfinder-input");
BrowseServer(input);
});
function BrowseServer(input) {
var finder = new CKFinder();
finder.selectActionData = input;
finder.selectActionFunction = function(fileUrl, data) {
input = data['selectActionData'];
console.log(input); //returns Object[input.form-control.ckfinder-input property value = "" attribute value = "null"]
console.log(fileUrl); //returns "/customer_images/header_images/home.jpg"
input.val() = fileUrl; // ReferenceError: invalid assignment left-hand side;
}
finder.resourceType = 'HeaderImages';
finder.removePlugins = 'basket';
finder.popup();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="bootstrap-filestyle input-group">
<input type="text" class="form-control ckfinder-input" name="ckfinder-input">
<span class="group-span-filestyle input-group-btn ckfinder-modal-button" tabindex="0">
<label class="btn btn-default">
<span class="icon-span-filestyle fa fa-cloud-upload"></span>
</label>
</span>
</div>
probably it's because your JavaScript is invalid. You cannot assign a value (fileUrl) to the output of function (input.val()) in:
js
input.val() = 'abc';
You should either:
a) if it is DOM Input Element:
input.value = 'abc';
b) if it's jQuery wrapper for DOM Element:
input.val( 'abc' );

Categories

Resources