I am looking to call my clear() JS function to clear the text values in some input fields on my webpage, but for some reason, the function doesn't appear to be called correctly. I believe this may be a scope issue, but I'm not sure.
Here is my markup, script and styling kept together for ease-of-use currently, but will be mended once scripting is finalized:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa
document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
alert('This equation has no real solution.')
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
}
function clear()
{
document.getElementById('variablea').value = "";
document.getElementById('variableb').value = "";
document.getElementById('variablec').value = "";
}
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button" onClick="calculateQuad()">
<input id="erase" value="Clear" type="button" onClick="clear()">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
You must rename the 'clear' method. Try naming it 'clearFields' or something. (;
Also, if you only want to reset the form fields you can also do this:
onClick="this.form.reset()"
You can avoid the issue with function naming entirely by using:
document.getElementById("calculate").onclick = function () {
...
};
document.getElementById("erase").onclick = function () {
...
};
This is actually a preferred method of adding event handlers by web developers because it avoids cluttering the HTML code with inline snippets of JavaScript while retaining cross-browser compatibility.
Related
How can I do this through the tag itself?
Change type from text to password
<input type='text' name='pass' />
Is it possible to insert JavaScript code inside the input tag itself to change type='text' to type='password'?
Try:
<input id="hybrid" type="text" name="password" />
<script type="text/javascript">
document.getElementById('hybrid').type = 'password';
</script>
Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).
You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.
I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84
To work in Internet Explorer:
dynamically create a new element
copy the properties of the old element into the new element
set the type of the new element to the new type
replace the old element with the new element
The function below accomplishes the above tasks for you:
<script>
function changeInputType(oldObject, oType) {
var newObject = document.createElement('input');
newObject.type = oType;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.value) newObject.value = oldObject.value;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
}
</script>
Yes, you can even change it by triggering an event
<input type='text' name='pass' onclick="(this.type='password')" />
<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">
Here is what I have for mine.
Essentially you are utilizing the onfocus and onblur commands in the <input> tag to trigger the appropriate JavaScript code. It could be as simple as:
<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>
An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:
<script type="text/javascript">
function password_set_attribute() {
if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" ||
document.getElementsByName[0].value == null) {
document.getElementsByName("login_text_password")[0].setAttribute('type','text')
document.getElementsByName("login_text_password")[0].value = 'Password';
}
else {
document.getElementsByName("login_text_password")[0].setAttribute('type','password')
}
}
</script>
Where HTML looks like:
<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>
let btn = document.querySelector('#btn');
let input = document.querySelector('#username');
btn.addEventListener('click',()=> {
if ( input.type === "password") {
input.type = "text"
} else {
input.type = "password"
}
})
<input type="password" id="username" >
<button id="btn">change Attr</button>
I had to add a '.value' to the end of Evert's code to get it working.
Also I combined it with a browser check so that the input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
document.getElementById("input_id").attributes["type"].value = "text";
This is a simple toggle with jQuery. It works also with the the ASP.NET MVC EditorFor() when you have a DataType.Password on the model property.
function showPassword() {
let password = $(".password");
if (password[0].type == "password") {
password[0].type = "";
}
else {
password[0].type = "password";
}
}
$(".show-pass").click(function (e) {
e.preventDefault();
var type = $("#signupform-password").attr('type');
switch (type) {
case 'password':
{
$("#signupform-password").attr('type', 'text');
return;
}
case 'text':
{
$("#signupform-password").attr('type', 'password');
return;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="password" class="show-pass">
This is not supported by some browsers (Internet Explorer if I recall), but it works in the rest:
document.getElementById("password-field").attributes["type"] = "password";
or
document.getElementById("password-field").attributes["type"] = "text";
You can try this:
const myTimeout = setTimeout(show, 5000);
function show() {
document.getElementById('pass').type = "text";
}
clearTimeout(myTimeout);
//html
<input type="password" id="password_input">
<i onclick="passwordDisplay()" class="ti-eye"></i>
//js
const input = document.getElementById("password_input")
function passwordDisplay() {
if (input.attributes["type"].value == "text")
input.attributes["type"].value = "password"
else
input.attributes["type"].value = "text"
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function changefield(){
document.getElementById("passwordbox").innerHTML = "<input id=\"passwordfield\" type=\"password\" name=\"password-field\" title=\"Password\" tabindex=\"2\" />";
document.getElementById("password-field".focus();
}
</script>
</head>
<body>
<div id="passwordbox">
<input id="password-field" type="text" name="password-field" title="Password"onfocus="changefield();" value="Password" tabindex="2" />
</div>
<input type="submit" name="submit" value="sign in" tabindex="3" />
</body>
</html>
i am trying to make a phonebook that has an add button when i click it it opens a form and there for now i want to display my name and phonenumber
now when i fillout these 2 fields and click on send it does not display it on the webpage
this is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PhoneBook</title>
<link rel="stylesheet" href="Css/Whole.css">
<script defer src="JavaScript/PU.js"></script>
</head>
<body>
<h1>PhoneBook</h1>
<div class="childContainer">
<div class="buttonsContainer">
<div>
<input type="search" placeholder="search" class="searchBar"></div>
<div class="buttonsRightSide"> <button value="submit" id="addBtn" class="addBtn">+</button>
<button value="submit" id="removeBtn" class="removeBtn">-</button>
<button value="submit" id="saveBtn" class="saveBtn">*</button></div>
</div>
<div class="formContainer">
<form class="addForm" id="addForm">
<h2>Create Contact</h2>
<label for="name">First name*:</label>
<input id="name" type="text" pattern="[A-Z][a-zA-Z]{3,7}" required><br>
<label for="phoneNumber">Phone number*:</label>
<input id="phone" type="number" pattern="[0][5][0-8][ -]?\d{7}" required><br>
<label for="Adress">Address:</label>
<input type="text" id="Address"><br>
<label for="Email">Email:</label>
<input type="email" id="Email"><br>
<label for="Description">Description:</label>
<textarea type="text" id="Description"></textarea><br>
<div class="sendCancelButtons">
<button type="submit" class="submitButton" id="submitButton">Send</button> <button value="submit"
class="cancelOverlay">Cancel</button></div>
</form>
</div>
<div class="outPutContainer">
</div>
</div>
</body>
</html>
and this is my javascript
"use strict";
function showOverlay(showButton, showContainer) { // this whole funciton opens up the overlay
const addButton = document.querySelector("." + showButton);
addButton.addEventListener("click", function addSomthing() {
document.querySelector("." + showContainer).style.display = 'block';
});
}
showOverlay("addBtn", "formContainer");
function cancelOverlay(cancelButton, showContainer) { //this dynamic funciton helps with closing overlays after we are done with the event
const removeOverlay = document.querySelector("." + cancelButton);
removeOverlay.addEventListener("click", function removeSomthing() {
document.querySelector("." + showContainer).style.display = 'none';
});
}
cancelOverlay("cancelOverlay", "formContainer");
function inputAndOutput() {
cancelOverlay("submitButton", "formContainer"); //this function helps me close the form window after i click on send
const form = document.getElementById("addForm");
form.addEventListener("submit", (e) => { //this is a submit event when the send button is pressed it makes an object and with the help of JSON it puts it into an array
let formOutput = {
name: document.getElementById("name").value,
phoneNumber: document.getElementById("phone").value
} //end of form
localStorage.setItem("formOutput", JSON.stringify(formOutput)); //array of obj
console.log(localStorage.getItem('formOutput')); //testing
displayOutput();
e.preventDefault(); //prevent the page to reload
} //end of Event
, );
}
inputAndOutput();
function displayOutput() {
if (localStorage.getItem('formOutput')) {
let {
name,
phoneNumber
} = JSON.parse(localStorage.getItem('formOutput'));
const output = document.getElementById("outPutContainer");
output.innerHTML = `
<ul>
<li>${name} </li>
<li>${phoneNumber} </li>
</ul>
`
}
}
any hints and suggestions are welcome and thanks in advance <3
Your JS code throws the error Uncaught TypeError: output is null.
The variable output gets defined here:
const output = document.getElementById("outPutContainer");
however, the container you want to get by id only has a class:
<div class="outPutContainer">
Change class="outPutContainer" to id="outPutContainer".
(Note: I found this solution using the Console tab of the Developer Tools of my browser. Press CTL+SHIFT+C in e.g. Firefox or Chrome and follow the errors/warnings. This is usually the fastest way to debug your scripts.)
I want to use HTML form elements in JavaScript. I used them like this but it doesn't work:
<form name="M">
<input name="in1" type="text" id="in1">
<input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
</form>
<script src="script.js"></script>
...and the JavaScript code was like this:
var s1 = 60;
function f1() {
``
if (document.M.elements[0] == s1) {
window.location = 'tick.htm';
} else {
window.location = 'cross.htm';
}
}
What is wrong here?
Just to give some clarification on why this was not working. In the test, document.M.elements[0] is a reference to the input object, not the value of the input. Using document.M.elements[0].value gives us the current value of the input.
//Ignore this, for display only.
function output(msg) {
var element = document.getElementById('output');
element.innerHTML = msg;
};
function f1() {
var s1 = 60;
if (document.M.elements[0].value == s1) {
output('Pass');
} else {
output('Fail');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<form name="M">
<input name="in1" type="text" id="in1">
<input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
</form>
<b id="output"></b>
</body>
</html>
this script opens a new page of an inputed website. how can i manipulate the window it appears in via check box? for example, if the check box for a scroll bar is checked, how do i add this to the new window?
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title></title>
<script>
function go(){
var myWindow;
var urlValue = document.getElementById("urlValue").value;
//radio buttons
if(yes.checked){
myWindow = window.open(urlValue);
}
else if (no.checked ){
myWindow = window.open(urlValue, "_self");
}
//checkbox loop
/*
for (i=0; i<document.myForm.checkGroup.length; i++){
if (document.myForm.checkGroup[i].checked==true)
alert("Checkbox at index "+i+" is checked!")
}
*/
}
</script>
</head>
<body>
<form name="myForm">
<p><label>Enter URL with http:// here: </label> <input id="urlValue" type="text"></p>
<p><label>Would you like to open a new window?<br>
<input name="yesNo" id="yes" type="radio">Yes<br>
<input name="yesNo" id ="no" type="radio">No </label></p>
<p><label>Other Options</label> <br>
<input name = "checkGroup" id="fullScreen" type="checkbox">Full Screen<br>
<input name = "checkGroup" id="scrollBar" type="checkbox">Scroll Bar<br>
<input name = "checkGroup" id="statusBar" type="checkbox">Status Bar<br>
<input name = "checkGroup" id="toolBar" type="checkbox">Tool Bar<br>
</p>
<p><input id="goButton" value="GO" type="button" onclick = "go()"></p>
</form>
</body>
</html>
This methods are deprecated in modern browser ...
There are no longer the Status Bar to hide, and you can no longer hide Scrollbars of the opened pages. Fullscreen also doesn't work as it did in old browsers, now there's a browser api that you can use to switch the browser to fullscreen mode, but you can't do that via the parent window, in a window.open().
Here is an example of how it would work in old browsers:
http://jsfiddle.net/MyajZ/
In modern browsers it still open the new window with no toolbars, and it switch to fullscreen mode, but immediately it goes back to normal state...
By the way, I found this simpler way to manage the checkbox's:
var params = "";
params += scrollBar.checked ? "scrollbars=yes," : "scrollbars=no,";
params += statusBar.checked ? "status=yes," : "status=no,";
params += toolBar.checked ? "toolbar=yes" : "toolbar=no";
params += fullScreen.checked? ",type=fullWindow,fullscreen" : "";
// ...
myWindow = window.open(urlValue, "Window Name", params);
An example result of the variable params:
scrollbars=no,status=no,toolbar=no,type=fullWindow,fullscreen
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" />
<title>Window opener</title>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var windowOpenerForm;
windowOpenerForm = $('#windowOpenerForm');
windowOpenerForm.submit(function (e) {
var url,
isNewWindow,
windowOptions,
windowTarget,
windowSpecs;
e.preventDefault();
url = 'http://' + $('#urlValue', windowOpenerForm).val();
isNewWindow = $('input[name="openNewWindow"]:checked',
windowOpenerForm).val();
windowOptions = extractWindowOption(
$('input[name="windowOptions"]',
windowOpenerForm));
windowTarget = isNewWindow === 'yes' ? '_blank' : '_self';
windowSpecs = [
'fullscreen=' + windowOptions.fullScreen,
'scrollbars=' + windowOptions.scrollBar,
'status=' + windowOptions.statusBar,
'toolbar=' + windowOptions.toolBar
].join(',');
window.open(url, windowTarget, windowSpecs);
});
function extractWindowOption(winOptions) {
var opt = {};
winOptions.each(function (index, elem) {
opt[$(elem).val()] = $(elem).is(':checked') ?'yes' : 'no';
});
return opt;
}
});
</script>
</head>
<body>
<form name="myForm" id="windowOpenerForm">
<p>
<label>Enter URL with http:// here: </label>
<input id="urlValue" type="text">
</p>
<p>Would you like to open a new window?<br>
<input name="openNewWindow" type="radio" value="yes" checked>Yes<br>
<input name="openNewWindow" type="radio" value="no">No
</p>
<p>Other Options<br>
<input name="windowOptions" value="fullScreen" type="checkbox">Full Screen<br>
<input name="windowOptions" value="scrollBar" type="checkbox">Scroll Bar<br>
<input name="windowOptions" value="statusBar" type="checkbox">Status Bar<br>
<input name="windowOptions" value="toolBar" type="checkbox">Tool Bar<br>
</p>
<p><input value="GO" type="submit"></p>
</form>
</body>
</html>
I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.
$('.barcodeField input').bind('keyup', function(event) {
if(event.keyCode==13){
$("this + input").focus();
}
});
I can't find anything that works on the net. And I've scoured the forums.
I've created a little function which can do what you need. This is the version I use so you may need to change the class names but you should get the idea.
<script type="text/javascript">
$(document).ready(function(){
$(".vertical").keypress(function(event) {
if(event.keyCode == 13) {
textboxes = $("input.vertical");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1]
nextBox.focus();
nextBox.select();
event.preventDefault();
return false
}
}
});
})
</script>
So basically:-
Get all the input fields matching .vertical
Find which is the current text box
Find the next one
Set the focus on that one
You should use:
$(this).next('input').focus();
try this:
(function($){
$.fn.enterNext = function(){
var _i =0;
$('input[type=text], select',this)
.each(function(index){
_i = index;
$(this)
.addClass('tab'+index)
.keydown(function(event){
if(event.keyCode==13){
$('.tab'+(index+1)).focus();
event.preventDefault();
}
});
})
$( "input[type=submit]",this ).addClass('tab'+(_i+1));
}})(jQuery);
for use:
$('form.element').enterNext();
in my case this is the best solution in that I got because the function .next() is strict with elements outside their branch DOM.
The best way is to force an index.
and sorry for my bad English...
Basically, you just need top have the DOM elements in some structure so that you can select the next one. I'd suggest exploiting tabindex, but anything that let's you have a defined order will work.
Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.
I've left in my debugging code:
try {
var inputs = $("input[id^=tpVal-]");
var sortedInputs = _.sortBy(inputs, function(element){
var tabIndex = $(element).attr('tabindex');//debugging
var id = $(element).attr('id');//debugging
console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
return parseInt($(element).attr('tabindex'));
});
$(sortedInputs).each(function (index, element) {
$(element).keyup(function(event){
if(event.keyCode==13) {
var $thisElement = $(element);//debugging
var nextIndex = index+1;//debugging
var $nextElement = $(sortedInputs[nextIndex]);
var thisId = $thisElement.attr('id');//debugging
var nextId = $nextElement.attr('id');//debugging
console.log("Advance from "+thisId+" to "+nextId);//debugging
if($nextElement!=undefined) {
$(sortedInputs[index + 1]).focus();
}
}
});
});
} catch (e) {
console.log(e);
}
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="122" class='TabOnEnter' tabindex="1" /><br>
<input id="123" class='TabOnEnter' tabindex="2" /><br>
<input type="text" name="abc" /><br>
<input type="text" name="abc1" /><br>
<input type="text" name="abc2" /><br>
<input type="text" name="abc3" class='TabOnEnter' tabindex="3" /><br>
<input class='TabOnEnter' tabindex="4" /><br>
<input class='TabOnEnter' tabindex="5" /><br>
<input class='TabOnEnter' tabindex="6" /><br>
<!-- <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>-->
<input type="submit" value="submit" class='TabOnEnter' tabindex="7">
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on("keypress", ".TabOnEnter", function (e)
{
//Only do something when the user presses enter
if (e.keyCode == 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
console.log(this, nextElement);
if (nextElement.length)
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut(); })
</script>
</body>
</html>
This code works for me
HTML:
<div class="row">
<div class="col-md-3"> Name </div>
<div class="col-md-3"> <input type="text" /> </div>
</div>
<div class="row">
<div class="col-md-3"> Email</div>
<div class="col-md-3"> <input type="email" /> </div>
</div>
Jquery code:
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
$(this).parent().parent().next('div').find('input').focus();
}
});