TypeError: - is not a function - javascript

I have this form which should hide another form:
<!--checkbox-->
<form method="POST" action="start.inc.php">
<span id="switch"><!--these are for css, the input matters-->
<label>
<input id="hide" name="hide" type="checkbox" onclick="hide()" /><!--error here-->
<span class="slider"></span>
</label>
<label for="hide">Do not set a password</label>
</span>
</form>
<!--this should be hidden-->
<form method="POST" action="start.inc.php">
<!--form stuff-->
<button type="submit" name="check">Set Password</button>
</form>
So I implemented a function like this:
function hide() {
var checkBox = document.getElementById("hide");
var form = document.getElementsByTagName("form")[1];
if (checkBox.checked == true)
{
form.style.display = "none";
} else {
form.style.display = "block";
}
}
It is written before the html, but even changing their order nothing changes...
The problem is that when I click on the checkbox the form doesn't disappear and I get the following error on the console:
(index):93 Uncaught TypeError: hide is not a function
at HTMLInputElement.onclick
Note: I'm a beginner in JS so please don't flame me if it was a stupid error
Thank you

The problem is that the name of the function is the same as the ID of the element. Element IDs become global variables, so hide is the <input> element rather than the function. The key to realizing this is that the error message doesn't say that hide is undefined, it says that it's not a function -- that means it's something else (in this case, a DOM element).
Give the function a name that's not the same as any element ID and it will work.

Related

Why can't select label with document.forms?

Is it possible to get label or div with document.forms ?
If yes. how ?
If not. Why ?
When I try it gives "undefined";
Example Code:
<form name="form1">
<div id="div1">
<label id="label1" for="uname">Username: </label>
<input type="text" id="uname" name="username" >
<button id="button1" onclick="func1()" >Okay!</button>
</div>
</form>
<script>
var form=document.forms['form1'];
function func1() {
event.preventDefault(); // -
console.log(form["uname"]); // gives input element
console.log(form["button1"]); // gives buttonn element
console.log(form["label1"]); // undefined
console.log(form["div1"]); // undefined
// I can get them like :
console.log(form["uname"].previousElementSibling); // gives label element
console.log(form["uname"].parentElement); // gives div element
// ...etc
// but, the questions is why I can't with document.forms
}
</script>
You can't select div because div are not part of form element. Source
var form=document.forms['form1'];
function func1() {
event.preventDefault(); // -
console.log(form["uname"]); // gives input element
console.log(form["button1"]); // gives buttonn element
console.log( form["uname"].labels[0] )
console.log(form["div1"]); // cant select div, because div are not form element
// I can get them like :
console.log(form["uname"].previousElementSibling); // gives label element
console.log(form["uname"].parentElement); // gives div element
// ...etc
// but, the questions is why I can't with document.forms
}
<form name="form1">
<div id="div1">
<label id="label1" for="uname">Username: </label>
<input type="text" id="uname" name="username" >
<button id="button1" onclick="func1()" >Okay!</button>
</div>
</form>
Content elements contained within a form have no relevance to the form being processed for being valid or submitted so there is no reason those content elements would need to be part of the form object.
You can however use form.querySelector() to target them
const form = document.forms.form1,
label = form.querySelector('#label1');
console.log('Label text = ', label.textContent)
<form name="form1">
<div id="div1">
<label id="label1" for="uname">Username: </label>
<input type="text" id="uname" name="username" >
<button id="button1" onclick="func1()" >Okay!</button>
</div>
</form>
It looks like form[elementId] returns the input element with that id. But that doesn't work as it only works for input elements. What you could do instead is form.elements, this is a HTMLColection which you could use with ids to get elements. form.elements[elementId].
Although that works, I would recomend you use document.getElementById. This way you don't need to understand old html/js jank. You would use it like this:
console.log(document.getElementById("uname")); // gives input element
console.log(document.getElementById("button1")); // gives button1 element
console.log(document.getElementById("label1")); // gives label element
console.log(document.getElementById("div1")); // gives div element

Unable to dynamically set a Input of type check box as required using javascript/jQuery

I am working on a sharepoint 2013 edit aspx form. now I have the following checkbox:
<span title="Yes" class="ms-RadioText">
<input id="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0" required="" type="checkbox">
<label for="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0">Yes</label>
</span>
now I want under certain conditions to set this checkbox as required, so users can not submit the form unless they check this checkbox. so I wrote the following javascript:
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
if (orderstatus0 == "Invoiced")
{
$('input[id^="UpdateOrder_"]').required;
var x = document.getElementById('UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0').required;
document.getElementById('UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0').required= true;
alert(x);
}
but currently no validation will be applied, even inside the alert i was excepting to get true, but I am getting false.. so can anyone advice on this please?
Add the code below into a script editor web part in the editform page.
<script src="//code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveAction(){
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
$("#updateordermsg").remove();
if (orderstatus0 == "Invoiced"){
if($('input[id^="UpdateOrder_"]').is(':checked')){
return true;
}else{
$('input[id^="UpdateOrder_"]').closest("td").append("<span id='updateordermsg' style='color:red'><br/>Please check the UpdateOrder.</span>");
return false;
}
}else{
return true;
}
}
</script>
You should use .att() jQuery function to set the attribute to the element.
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
$('input[id^="UpdateOrder_"]').attr("required", "required");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span title="Yes" class="ms-RadioText">
<input id="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0" type="checkbox">
<label for="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0">Yes</label>
</span>
<input type="submit" value="Submit">
</form>

Check to see if a button is clicked on... not working

Just a very brief explanation of what a part of my code does:
I have two buttons that do different things.
One of them lets the user search through the table/database for whatever he/she wants to search for
The other lets the user insert things into the database
WHAT I'M TRYING TO DO:
I'm trying to check to see which button the user clicked on so that the appropriate code will be executed.
I've been looking around and pretty much everywhere I go, people are suggesting to use isset(), but it's not working for me. Perhaps I don't fully understand what isset() does, but doesn't it basically check to see whether a variable is set?
Here's my code:
<script>
function show(x, y){
<!-- Do something -->
}
</script>
<form>
<button name = "sButton" type = "button" onclick = 'show("searchForm", "insertForm");'>Perform Search</button>
<button name = "iButton" type = "button" onclick = 'show("insertForm", "searchForm");'>Insert Data</button>
</form>
<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">
<!-- Do something -->
</form>
<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">
<!-- Do something -->
</form>
<!-- This is the test2.php page -->
if(isset($_POST['sButton'])){
<!-- Do something -->
}
else{
<!-- Do something -->
}
To test it, I had the if statement print "Checked" and the else print "Not checked". When I run my code, it prints "Not checked". What am I doing wrong and what should I be doing?
Thanks in advance!
You are not passing your buttons sButton or iButton into test2.php because your second and third form do not have them as input. Only inputs inside each particular form will be submitted. and your form that has the buttons has no action only the buttons call the JS function.
What I suggest you do is to add hidden fields for each form that you are submitting to test2.php as follows:
<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">
<input type="hidden" name = "sButton" value="sButton" />
<!-- Do something -->
</form>
<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">
<input type="hidden" name = "iButton" value="iButton" />
<!-- Do something -->
</form>
This way your test2.php should work.
Add an
<input type="hidden" name="sButton" />
into the search form, and a
<input type="hidden" name="iButton" />
into the insert form.
After that. You need to submit the (selected) form in the show(...) javascript function
Use this:
onclick = 'show(this.name, "searchForm", "insertForm");'
Example:
<button name = "sButton" type = "button" onclick = 'show(this.name, "searchForm", "insertForm");'>Perform Search</button>
function show(name, x, y){
alert(name);
if(name === "sButton"){
do this....
}
}
Output:
sButton
DEMO
http://codepen.io/tuga/pen/RPNaXY
I'm not sure what you're trying to do, but I don't see why the buttons are in a form at all. Consider attaching the listeners dynamically, adding a name or ID to the buttons so you can tell which one was clicked then hide or show the forms depending on which was clicked:
// The buttons don't seem to need to be in a form, so use some other
// container so you don't need to worry about a useless form being
// submitted
<div id="buttonContainer">
<button id="searchButton">Perform search</button>
<button id="insertButton">Insert data</button>
</div>
// Forms for testing
<form id="searchForm"><input value="search"></form>
<form id="insertForm"><input value="insert"></form>
and the code:
<script>
// Hide and show forms depending on which button was clicked using the
// button's ID
function showForm(event) {
// If the search button was clicked, show the search form and hide the
// input form
if (/search/.test(this.id)) {
document.getElementById('searchForm').style.display = '';
document.getElementById('insertForm').style.display = 'none';
// If the insert button was clicked, do the opposite
} else {
document.getElementById('searchForm').style.display = 'none';
document.getElementById('insertForm').style.display = '';
}
}
// Attach listeners to the buttons
window.onload = function() {
Array.prototype.forEach.call(document.querySelectorAll('#searchButton, #insertButton'),
function(button) {
button.addEventListener('click', showForm, false);
}
);
// Hide the forms
Array.prototype.forEach.call(document.querySelectorAll('#searchForm, #insertForm'),
function(form) {
form.style.display = 'none';
}
);
}
</script>

Uncaught Type Error: Cannot read property, JS executing before page renders

I am receiving the following error in my console:
Uncaught TypeError: Cannot read property ‘value’ of null
What I'm attempting to do is copy text input from one input box into another, when you click the checkbox the value of one input will be copied into another input.
HTML
<input name="stry" type="text" id="stry"/>
<input type="checkbox" name="sendsms" onclick="CopyStory(this.form)">
<div id="container">
<input type="text" class="form-control" name="body">
</div>
JS
function CopyStory(f) {
if(f.sendsms.checked == true) {
f.stry.value = f.body.value;
}
}
I believe the problem is that the code is executed before the elements load because I have a javascript alert modal pop-up which prevents the page from loading unless you press 'Ok'
Alert JS
$('#container').fadeOut('fast').delay(7000).fadeIn('fast');
alert("This page is loading....");
I've tried wrapping it around document.ready(function blah... but then it gives me an error that: " 'CopyStory' is not defined".
Any suggestions?
Take a look at this JSFiddle.
JS
function copyStory(ch) {
if(ch.checked)
var text1 = document.getElementById("stry").value;
else
text1='';
document.getElementById("second").value = text1;
}
$('#container').fadeOut('fast').delay(7000).fadeIn('fast');
alert("This page is loading....");
HTML
<input name="stry" type="text" id="stry"/>
<input type="checkbox" name="sendsms" onclick="copyStory(this)">
<input type="text" class="form-control" id="second" name="body">
<div id="container">
</div>
You are not using the form tags and trying to access a form..!
Try this,
function CopyStory(f) {
if(f.sendsms.checked == true) {
console.log(f.body.value);
f.stry.value = f.body.value;
}
}
<div>
<form>
<input name="stry" type="text" id="stry"/>
<input type="checkbox" name="sendsms" onclick="CopyStory(this.form)">
<div id="container">
<input type="text" class="form-control" name="body">
</form>
</div>
Just put the js script inside <head></head>
First, wrap your code in $(function(){ //code here }); to execute your js after page loads.
About 'CopyStory' is not defined:
when you define function like:
$(function(){
function CopyStory(){ //... }
});
CopyStory is not visible in global scope, so if you want to fix your problem just change defenition to:
$(function(){
window.CopyStory = function(){ //... }
});
p.s. assign a variable to window propery is the only way to define global variable inside a local scope.

Radio buttons checked changing submit text

My site structure consists on an index.php which is styled by a css file. It then includes the following php code in a separate file:
<?php include("globals.php"); ?>
<form action="<?php echo $website.$relative_string;?>" name="subscribe" onsubmit="javascript:return checkEmail(this);" method="post">
<div id="cell8" class="titlecell2"><h3>Email:</h3></div>
<div id="cell9" class="inputcell2">
<input type="text" class="inputfield2" name="email" value="Your Email..." id="email2" maxlength="255" onfocus="this.value='';">
</div>
<div id="cell10" class="textcell3">
<input name="group" type="hidden" id="group[]" value="<?php echo $group; ?>">
<input name="subscribe" id="sub" type="radio" value="true" checked>
</span>Subscribe </p>
</div>
<div id="cell11" class="buttoncell">
<button type="submit" name="Submit2" value="Join" id="submitButton2">
<span>OK</span>
</button>
</div>
<div id="cell8" class="textcell4">
<input type="radio" name="subscribe" id="unsub" value="false">
</span>Un-Subscribe </p>
</div>
</form>
It appears on screen with no problems in the correct layout as my css style sheet. What I would like this to do is when I select the "Subscribe" radio button the submit button text "OK" changes to "Join". When I click on the Unsubscribe button text "OK" or "Join" changes to "Leave".
I tried to make some code from research:
if(document.getElementById('sub').checked) {
document.write("<span>Join</span>"
}
else if(document.getElementById('unsub').checked) {
document.write("<span>Leave</span>)
}
I think this kind of worked in that it changed to Join (replacing the OK line, but obviously didn't update on clicking unsubscribe. I guess it would update on refreshing the page if my default wasn't join. I guess I need to do some form of onclick but then I have no idea how to adjust that span ok bit.
Please help?
Many thanks Chris
Here is a solution in plain JavaScript without jQuery. It avoids the unnecessary overhead.
This should work, but I haven't had a chance to test it:
var sub = document.getElementById('sub'); // Save element to a variable, so you don't have to look for it again
var unsub = document.getElementById('unsub');
var btn = document.getElementById('submitButton2');
sub.onchange = function() //When sub changes
{
if(sub.checked) //If it's checked
{
btn.innerHTML = "<span>Join</span>"; // Set button to Join
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
unsub.onchange = function() //When unsub changes
{
if(unsub.checked) //If it's checked
{
btn.innerHTML = "<span>Leave</span>"; // Set button to Leave
}
else // If not..
{
btn.innerHTML = "<span>OK</span>"; // Set button to OK
}
}
However, you should not do it like this.
You should combine the two radio buttons into a radio group.
In that case you will listen for radio group to change, get the value of the radio group, set button text according to the value.
if you label your <span>OK</span> to something like <span id="your_id">OK</span> then added a class to your radio button like this <input class="your_class" type="radio" name="subscribe" id="unsub" value="false"> them...
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#your_class").change(function () {
if ($(this).is(':checked')) {
$("#your_id").text('Join');
}else {
$("#your_id").text('Leave');
}
});
</script>
This was all written in the browser so let me know if there are any problems.

Categories