I am completely brand new to Javascript. In fact, I'm just an Objective-C programmer looking to implement just a little Javascript into one of my apps. So, the problem is for whatever reason when I call my first function, nothing happens there I don't get the alert. When I call my second function I only get the alert, the button isn't actually clicked.
Code:
function myFunction(username, password) {
alert("Data will be entered");
document.getElementById('ctl00_plnMain_txtLogin').value = username;
document.getElementById('ctl00_plnMain_txtPassword').value = password;
}
function click() {
alert("The button was clicked");
document.getElementById("ctl00_plnMain_Submit1").click();
}
I can seem to run just a regular alert fine, but nothing else??? Is there something wrong in my function?
If it helps, on the website here is the "username" box:
<input name="ctl00$plnMain$txtLogin" type="text" maxlength="50" id="ctl00_plnMain_txtLogin" tabindex="1">
"password" box:
<input name="ctl00$plnMain$txtPassword" type="password" maxlength="255" id="ctl00_plnMain_txtPassword" tabindex="2">
the button:
<input onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); " name="ctl00$plnMain$Submit1" type="submit" id="ctl00_plnMain_Submit1" tabindex="3" value="Log In" title="Log in">
-- EDIT
Also, I am starting the functions through my objective C code. I grab a js file, then I am able to use its functions on a webpage.
I would recommend using a DOM abstraction library like jQuery
jQuery provides an 'on' method, it's used to bind events to DOM elements:
$('#ctl00_plnMain_Submit1').on('click', function (event) {
alert("The button was clicked");
}
It also provides a nice abstraction for collecting input values:
var userName = $('#ctl00_plnMain_txtLogin').val();
You can also use it to set the value of an input:
$('#ctl00_plnMain_txtLogin').val('New Value for This Input');
Populating inputs with a function:
function populateInputs (username, password) {
$('#ctl00_plnMain_txtLogin').val(username);
$('#ctl00_plnMain_txtPassword').val(password);
}
I am guessing you want the click function to be called when the button is clicked
You need to specify that then
<input onclick="click()" ....
Related
So basically, I want to enter a certain string into a text-box, and check what it is. It's basically for a command system that I'm trying to implement. There's a little Terminal pop-up and there is a text-box in it waiting for a command. This is the HTML I used to make the text-box inside a form:
<form id="command-input">
<input type="text" placeholder="Enter Command" id="command-box">
<input type="submit" style="display: none">
</form>
I made the submit invisible so you could press enter and it would submit the form. Here is the JavaScript I'm using:
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
I want to make it to where if I type "windows" into the command box and hit enter, it will change my stylesheet. The people on this website are smart, so I once again am asking for help. Thanks for contributing!
You will need to check with an event. Assuming this is in the plain tags; you can use the following:
var inputbox = document.getElementById('command-input');
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
inputbox.addEventListener('input', function (evt) {
if (this.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
});
Edit:
you can do this as well. Change the event to "onsubmit" if you want enter key to trigger.
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
document.getElementById('command-input').addEventListener(
'keyup',
function(eve){
if (eve.target.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
},
false
);
If you want to keep the changes even after the page refresh you might have to keep the file path in the localstorage and use that in dom load event.
Also, you really dont need to wrap this in a form tag. You can use a simple div and this is not triggered by a form submit.
You could create a function that you can call on form submission as explained here at https://www.w3schools.com/jsref/event_onsubmit.asp.
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
}
</script>
edit- the problem was in the redirection and Solved by Ahmed with the immediately invoked Function Expression aka IIFE
problem redirecting to another page, values are a string and the integer "CharFields" .. else statement works fine but the if statement when I type it correct the page just refreshes and nothing happens.
I made java function to get variables from a user input trcode
and made Django print the model in an input value those two works fine I tested them with printing,, the problem is in comparing the values and redirecting to the another URL
function readText () {
var value1 = document.getElementById("trcode").value;
var value2 = document.getElementById("trfcode").value;
if (value1 === value2) {
location.href="http://127.0.0.1:8000/myposts";}
else {
alert("You typed: " + "Wrong Password");}
}
<form onsubmit="return readText();">
<tr><td height="18" class="subheaderboldtext"> Enter Code:
<input id="trcode" maxlength="8" class="box">
<input class="submit" type="submit" value="SUBMIT">
<button id="trfcode" value="{{ user.profile.trf_code }}">z</button>
I have made some changes to your code. The button with id trfcode is being assigned a value already called user.profile.trf_code. If you replace it with the value you are trying to match it will work fine. For testing purposes I have changed your code a bit and have assigned it a value of z. Upon typing z in input and clicking submit gives me a +ve result.
I am guessing your main concern is reading the value of user-profile user.profile.trf_code. So you may wanna debug this and find out if you are getting a proper value back which you are expecting.
Few tips for debugging. When you are in such a situation, please first look at the values of each element and find out even if you are getting the values back. Then next step to find out if you are getting the same values or not and so on.
Putting value="z" makes this working. Please note that I have added extra logs and an alert. Please feel free to remove it.
EDIT:
If you see in the form, I have added a function wrapping your function. This is called immediately invoked Function Expression aka IIFE which basically is a function and can be called right there. Form creates an event, that event has a method called preventDefaults() which prevents the page from reloading or refreshing upon everytime you submit. I have wrapped your method under an IIFE to prevent the page from refreshing and then called your function. I would highly recommend you adding this as a part of your question though.
Your form,
<form onsubmit="return (function(event) { event.preventDefault(); readText()}) (event)">
<tr>
<td height="18" class="subheaderboldtext"> Enter Code:
<input id="trcode" maxlength="8" class="box">
<input class="submit" type="submit" value="SUBMIT">
<!-- <img src="/static/guest/images/querybutton.png" alt="Query Button" /> -->
</td>
</tr>
</form>
<button id="trfcode" value="z">z</button>
Javascript given below,
function readText() {
var value1 = document.getElementById("trcode").value;
var value2 = document.getElementById("trfcode").value;
console.log(`value1 = ${value1}`);
console.log(`value2 = ${value2}`);
if (value1 === value2) {
// location.href = "http://127.0.0.1:8000/myposts";
console.log(`I am good`);
alert(`You typed: ${value1}`);
} else {
console.log(`I am in else`);
alert("You typed: " + "Wrong Password");
}
}
I am a total newbie to JavaScript, trying to find my way on form validation. I have been reading books as well as online tutorials and I found the following code online that is, in my opinion, very elegant and maintainable. Unfortunately, my skills in JavaScript are not good enough to understand everything. I am here to ask your help to understand the different functions defined.
I would like also to call the InstantValidation function on an event (onSubmit event) calling it in an independent .js file (based on event listener), so might you please also help me to call the function appropriately?
Here is the code:
<html>
<body>
<form id="myform" action="#" method="get">
<fieldset>
<legend><strong>Add your comment</strong></legend>
<p>
<label for="author">Name <abbr title="Required">*</abbr></label>
<input name="author" id="author" value=""
required="required" aria-required="true"
pattern="^([- \w\d\u00c0-\u024f]+)$"
title="Your name (no special characters, diacritics are okay)"
type="text" spellcheck="false" size="20" />
</p>
<p>
<label for="email">Email <abbr title="Required">*</abbr></label>
<input name="email" id="email" value=""
required="required" aria-required="true"
pattern="^(([-\w\d]+)(\.[-\w\d]+)*#([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2})$"
title="Your email address"
type="email" spellcheck="false" size="30" />
</p>
<p>
<label for="website">Website</label>
<input name="website" id="website" value=""
pattern="^(http[s]?:\/\/)?([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2}(\/([-~%\.\(\)\w\d]*\/*)*(#[-\w\d]+)?)?$"
title="Your website address"
type="url" spellcheck="false" size="30" />
</p>
<p>
<label for="text">Comment <abbr title="Required">*</abbr></label>
<textarea name="text" id="text"
required="required" aria-required="true"
title="Your comment"
spellcheck="true" cols="40" rows="10"></textarea>
</p>
</fieldset>
<fieldset>
<button name="preview" type="submit">Preview</button>
<button name="save" type="submit">Submit Comment</button>
</fieldset>
</form>
<script type="text/javascript">
(function()
{
//add event construct for modern browsers or IE
//which fires the callback with a pre-converted target reference
function addEvent(node, type, callback)
{
if(node.addEventListener)
{
node.addEventListener(type, function(e)
{
callback(e, e.target);
}, false);
}
else if(node.attachEvent)
{
node.attachEvent('on' + type, function(e)
{
callback(e, e.srcElement);
});
}
}
//identify whether a field should be validated
//ie. true if the field is neither readonly nor disabled,
//and has either "pattern", "required" or "aria-invalid"
function shouldBeValidated(field)
{
return (
!(field.getAttribute('readonly') || field.readonly)
&&
!(field.getAttribute('disabled') || field.disabled)
&&
(
field.getAttribute('pattern')
||
field.getAttribute('required')
)
);
}
//field testing and validation function
function instantValidation(field)
{
//if the field should be validated
if(shouldBeValidated(field))
{
//the field is invalid if:
//it's required but the value is empty
//it has a pattern but the (non-empty) value doesn't pass
var invalid =
(
(field.getAttribute('required') && !field.value)
||
(
field.getAttribute('pattern')
&&
field.value
&&
!new RegExp(field.getAttribute('pattern')).test(field.value)
)
);
//add or remove the attribute is indicated by
//the invalid flag and the current attribute state
if(!invalid && field.getAttribute('aria-invalid'))
{
field.removeAttribute('aria-invalid');
}
else if(invalid && !field.getAttribute('aria-invalid'))
{
field.setAttribute('aria-invalid', 'true');
}
}
}
//now bind a delegated change event
//== THIS FAILS IN INTERNET EXPLORER <= 8 ==//
//addEvent(document, 'change', function(e, target)
//{
// instantValidation(target);
//});
//now bind a change event to each applicable for field
var fields = [
document.getElementsByTagName('input'),
document.getElementsByTagName('textarea')
];
for(var a = fields.length, i = 0; i < a; i ++)
{
for(var b = fields[i].length, j = 0; j < b; j ++)
{
addEvent(fields[i][j], 'change', function(e, target)
{
instantValidation(target);
});
}
}
})();
</script>
</body>
</html>
In particular, the following code is not toally clear to me:
function addEvent(node, type, callback)
{
if(node.addEventListener)
{
node.addEventListener(type, function(e)
{
callback(e, e.target);
}, false);
}
else if(node.attachEvent)
{
node.attachEvent('on' + type, function(e)
{
callback(e, e.srcElement);
});
}
}
Any help (even a very brief explanation) would be highly appreciated !
#1 That's an event handler abstraction layer.
That one code section acts as an event handler, but works across various different browsers.
Most browsers use the addEventListener way of adding an event handler.
Some Internet Explorer versions use attachEvent: http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx
The function allows both ways to be used.
It has you pass in...
... the element you want to add an event to (node)
... what type of event you want to handle (type)
... what code you want executed by an event (callback)
Browser events: http://eloquentjavascript.net/chapter13.html
Abstraction layers: http://en.wikipedia.org/wiki/Abstraction_layer
Browser events are things like a page fulling loading (onload), something being clicked (onclick), an input being changed (onchange), a cursor going over an element (onmouseover), etc...
http://www.w3schools.com/js/js_htmldom_events.asp
#2 How to go about invoking validation onSubmit...
//now bind a change event to each applicable for field
The code below that goes through each input and textarea element and adds validation to each one with the onchange event. But what you want to do is validate onsubmit, which requires something like this, below the other addEvent call:
addEvent("myform","onsubmit", function(){
//de Go field by field and validate.
//de If all the fields pass, return true.
//de If one or more fields fail, return false.
})
If you want, you can even remove the onChange events. That is your choice. The main thing here is that you need to make sure to only validate the fields inside the form itself, which you can look at this answer for more information about: Best Practice: Access form elements by HTML id or name attribute? ... loop through all the elements, and validate each one within the addEvent I mentioned above which must return true or false to either allow the form to be submitted, or stop the submission and show that there were validation errors.
Please remember! As a personal bit of advice... On the server-side you still want to do validation, even if you have client-side validation. Browsers are easy to manipulate, so you might still have bad data sent to the server. Always, always do server-side validation regardless of client-side.
It just looks like a cross-browser function that attaches a handler (instantValidation) to the "change" or "onchange" events of all input and textarea controls.
I say cross-browser because of the presence of two separate event subscription methods. attachEvent is for older IE browsers (5-8) and addEventListener is generally for all modern browsers.
This addEvent function checks for the presence of said functions and uses whatever is available, giving preference to the "modern" way.
This is cross-browser code for attaching event handlers to the events raised by a DOM element. The function (addEvent) has arguments as follows:
node: the DOM node object to which an event will be attached (retrievable via a function like getElementById)
type: The event name, such as change, focus etc.
callback: The function to call when the event is raised.
This line: if(node.addEventListener) checks whether the node has a property called addEventListener. If the property is there, it behaves the same as true and the if block is entered.
The check for addEventListener is done because different browsers implement this event attachment function differently. Namely, IE versions before IE9 use only attachEvent.
<script>
$(function() {
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
})
</script>
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name"><input type="submit" id="button">
</form>
</div>
Does not print name in console, what am I doing wrong here?
The problem right now is that the code you've written is executed immediately when the page loads.
From the way your code looks, it looks like you actually want the form's button to do the console log.
I've altered your code a bit, but here's how you'd:
Select the Form and the Input
Declare the variable out of the scope
Bind onto the form's submit event
Prevent it from actually submitting
And logging to console per your example
Altered code below:
<script>
$(function() {
// Save a reference to the input
var input = $("input[name=first_name]"),
// Get the form itself
form = $("form[name=info]"),
// Storage for your first_name outside of the scope
first_name = false;
// Bind to the submit event on the form
form.bind('submit', function() {
// Set the first_name to the input's value
first_name = input.val();
// Log it out (per your example)
console.log(first_name);
// Return false to prevent the form from posting
return false;
});
});
</script>
<div id="content">
<form name="info">
First Name:
<input type="text" id="first_name" name="first_name">
<input type="submit" id="button">
</form>
</div>
I'm not saying this is the best way to handle whatever you're attempting to do with the form, realistically you shouldn't need an ID on the button, and probably would want to replace the NAME on the form with an ID for the selector. Also using an ID selector to get the input would be recommended as well, as ID selectors are faster than [name=something] selectors. (Thanks gnarf for the comment!)
The variable scoping is also probably somewhat strange in your example, but the above code should be good for learning :)
The method as you've written it only runs once, after the page loads. At that point the input element doesn't contain a value (i.e. $("#first_name").text() == ''). You can bind the logging statement to the keyup event of the element, to see the text that's being entered into it.
$(function() {
// this code only runs once
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
$('#first_name').keyup(function() {
// this code fires everytime a key is released on the element
console.log($(this).val());
});
})
Demo on plnkr
Here is the JSFiddle for your code.
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name" value="something">
<input type="submit" id="button">
</form>
</div>
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val());
});
'Something' is the default value.' Try other words in the text box and you will see the new value in console.
As per your code, you are getting correct results.
Your defined function is never called because you have not attached any events to it.
I have modified your code and you can check it working here
$(document).ready(function(){
$("#first_name").focusout(function(){
var first_name = $(this).val();
alert(first_name);
});
});
$('#content form').on('submit', function () {
console.log(
$(this).find('input[name="first_name"]').val()
);
return false;
});
edit: you must run your jQuery selection after you have inputted something into the input field. Right now when you run it, it is empty
edit: try using this 'on' from the jQuery docs
http://api.jquery.com/on/
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val(););
}
Ok so i have a form that has three input boxes, at the moment they're text, but they will be changed to password. When the submit button is pressed i want the for to send the form data to an Ajax script.
I have this working with just one parameter the button looks like this:
<input type="submit" name="submit" value="Submit"
onClick="return pass(this.form.oldPass.value;">
Now i've tried adding the 'this.form' part three times because thats how many parameters the function would take but it just doesn't seem to do anything:
<input type="submit" name="submit" value="Submit"
onClick="return pass(this.form.oldPass.value,
this.form.newPass.value,
this.form.newPassCheck);">
Is this the right way to go about passing form data to a script? is there another way around it or am i just doing something wrong here?
thanks for the help, if you need anymore code i'll add it.
try this one. (you need jquery to do this.)
<form>
old pass <input type="password" id="old_pass" />
new pass <input type="password" id="new_pass" />
new pass confirmation <input type="password" id="new_pass_confirm"/>
</form>
in your .js file , write this:
$(document).ready(function(){
var old_pass = $('#old_pass').val();
var new_pass = $('#new_pass').val();
var new_pass_confirm = $('#new_pass_confirm').val();
//then call your method with those vars as parameter
anyMethod(old_pass, new_pass, new_pass_confirm);
});
//this is your function
function anyMethod(old_pass, new_pass, new_pass_confirm)
{
//put your validation code or ajax call here...
}
Add id for each of your input boxes and you can get value in function, like:
function pass() {
var old = document.getElementById("yourOldPassId").value;
var new = document.getElementById("yourNewPassId").value;
var newConfirm = document.getElementById("yourNewConfirmPassId").value;
}
Did you mean something like this
Give the inputs some ids and get the data from there.
Something like:
<input type bla bla id="whateverId0" />
For each input.
The submit should have something like onclick="whateverFunction()"
The js should look like:
function whateverFunction()
{
val0 = document.getElementById('whateverId0');
// For all 3 values.
// Do whatever you want with them.
}
I believe that you should add an onSubmit listener to your form. There are good js frameworks out there like jquery which are easy to use. That way you can make a listener which runs a function when you submit your form. In that function you can extract the data to json for example and ajax it to your server.
info about jquery
jquery ajax
how to extract form data