Getting img.src value (path name) - javascript

I have a form for a registration page. The form contains an image that changes its src dependant on a situation.
Within a script which activates upon submission of the form, I want the form to call an alert if that image has a particular src, so I need a way of retrieving and comparing the value.
HTML:
<form action="register_submit.php" method="post" name="mainform" enctype="multipart/form-data" onSubmit="return checkForm(this);return false;">
JS:
function checkForm(f)
{if ([image src value] == "pictures/apic.png")
{
alert("error picture is apic");
return false;
}
else
{
f.submit();
return false;
}
}
Here is the relative code in full:
<script type="text/javascript">
function checkForm(f)
{if ([image src value] == "pictures/apic.png")
{
alert("error picture is apic");
return false;
}
else
{
f.submit();
return false;
}
}
</script>
<form action="register_submit.php" method="post" name="mainform" enctype="multipart/form-data" onSubmit="return checkForm(this);return false;">
<div class="required">
<label for="first_name">*First Name:</label>
<input type="text" name="first_name" id="first_name" class="inputText" onkeyup="checkFName(this.value);" onblur="checkFName(this.value);" maxlength="20" size="10" value="" />
<img id="FName_Status" name="FName_Status" src="/pictures/bad.png" style="margin-left:5px; position:absolute;" alt="FName_Status" />
</div>
(OTHER OBJECTS)
</form>
<input type="submit" name="sub" class="inputSubmit" value="Submit ยป"/>

Use this:
if (document.getElementById('FName_Status').getAttribute('src') == "pictures/apic.png")

Add an ID tag to your image (if it doesn't already have one), eg:
<img src="pictures/apic.png" id="imageId" />
Then you can reference it as follows:
if (document.getElementById("imageId").src == "pictures/apic.png")
{
...
}
EDIT
Working example here: http://jsfiddle.net/2Wtkn/2/

Related

How to validate input using external javascript?

Im doing app based on phonegap. Im trying t validate my input with external javascript file. But getting error validateForm is not defined at HTMLFormElement.onclick. What's wrong with my code?
HTML
<div data-role="page" id="page1">
<div data-role="header">
Back
<h2>Add New</h2>
</div>
<!-- main -->
<div data-role="main" class="ui-content">
<form name="myform" onclick="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
<button type="button" id="but_submit">Submit</button>
</form>
</div>
<!-- footer -->
<div data-role="footer">
<h2>mine</h2>
</div>
</div>
Code from external javascript
function validateForm(){
var x = document.forms["myform"]["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
}
Use onsubmit, and by passing this from the event handler, you can use it instead for document.forms[....]
HTML
<form name="myform" onsubmit="return validateForm(this)" method="post">
Script
function validateForm(theform){
var x = theform["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
}
And by using event listeners it can be even more maintainable (and unobtrusive)
HTML
<form name="myform" method="post">
Script
window.addEventListener('load', function() { /* fires when page been loaded */
document.querySelector('[name="myform"]').addEventListener('submit', function(e) {
var x = e.target["myname"].value;
if (x==null || x==""){
alert("enter name");
return false;
} else{
return true;
}
});
});
You should use the onchange event because onclick triggers before having a chance to actually write something in the input.
This way you can deal with the validation after the value has changed and not wait for the form to be submitted.
Or if you want to validate just before submit you can use the onsubmit event like LGSon suggested.
function validateForm() {
var x = document.forms["myform"]["myname"].value;
if (x == null || x == "") {
alert("enter name");
return false;
} else {
console.log(true, x);
return true;
}
}
<form name="myform" onchange="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name">
<button type="button" id="but_submit">Submit</button>
</form>
Use below html code:
<form name="myform" onsubmit="return validateForm()" method="post">
Name : <input type="text" name="myname" id="my_name" placeholder="Enter Your Name" >
<button type="button" id="but_submit">Submit</button>
</form>

JavaScript custom validation not working

Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}

Validating form element in JS in a page which has many forms

JS prints incoming form names correctly however I'm getting error message below when validating form element. Form names are generated dynamically in a loop.
Thanks
ERROR
TypeError: document.form_name is undefined
JS
function validate_update(form_id)
{
var form_name = 'form_bottom_update_' + form_id;
//alert (form_name); //Prints form name correctly as form_1, form_2, form_3
var bg_name = (document.form_name.bg_name.value).replace(/ /gi, "");
if (bg_name == '')
{
alert('Enter a Name');
return false;
}
return true;
}
HTML
<form name="form_1" action="update.php" method="POST" onsubmit="return validate_update(1);">
<input type="text" name="bg_name" value="" />
<input type="submit" name="submit" value="Update" />
</form>
<form name="form_2" action="update.php" method="POST" onsubmit="return validate_update(2);">
<input type="text" name="bg_name" value="" />
<input type="submit" name="submit" value="Update" />
</form>
<form name="form_3" action="update.php" method="POST" onsubmit="return validate_update(3);">
<input type="text" name="bg_name" value="" />
<input type="submit" name="submit" value="Update" />
</form>
Shoudn't that:
var bg_name = (document.form_name.bg_name.value).replace(/ /gi, "");
be:
var bg_name = (form_name.bg_name.value).replace(/ /gi, "");
You print the form_name variable, but later you use document.form_name which is a different object.
Either use the later, or when assigning the bg_name, use the document:
document.form_name = 'form_bottom_update_' + form_id;
Changes approach to solve the problem. Form name remain same, text name becomes dynamic.
function validate_update(form_id)
{
var element_name = 'bg_name_' + form_id;
var bg_name = (document.getElementsByName(element_name)[0].value).replace(/ /gi, "");
if (bg_name == '')
{
alert('Enter a Name');
return false;
}
return true;
}
<form name="form" action="update.php" method="POST" onsubmit="return validate_update(2);">
<input type="text" name="bg_name_2" value="" />
<input type="submit" name="submit" value="Update" />
</form>
you haven't used form_id anywhere in your html so how could you call it in javascript

Forward page request using JavaScript functions return values?

Here is the related part of code:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" >
<div>
<hr/><a name="d2"></a>
<h2>CMS Sign In Page</h2>
<p>Passing parameters to the Web Service:</p>
<label>Your username: </label><input type="text" name="username" id="username" value="elthefar" />
<label>Your password: </label><input type="password" name="password" id="password" value="workandwork" />
<input type="button" value="Sign In" onclick="var r = SignIn(); if (r == 0) document.forms[0].action = 'temp2.jsp'; return true;" />
I want my form to forward to temp2.jsp if SignIn return 0, otherwise to temp.jsp. but the above code doesn't forward to any page.
You can add a onsubmit event to you form like this:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" onsubmit="return myfunction();">
and then use a simple submit button in your form.
<input type='submit' value='Sign In' />
in this case, when you click on submit button, the function will fire and in that function you can do what ever you want to do like this:
<script language='javascript'>
function myfunction(){
var r = SignIn();
if(r == 0)
document.forms[0].action = 'temp2.jsp';
return true;
}
</script>
Did you mean to use input type="submit"? Or call document.forms[0].submit();?
Change your form to this
<form id="frmDemo" name="frmDemo" method="post">
And change button to submit
<input type="submit" name="Submit" onClick="Validate()" value="Submit" />
And use your javaScript
<script language='javascript'>
function Validate(){
var r = SignIn(); // assuming, you have some implementation for SignIn() method
var frm = document.getElementById("frmDemo") || null;
if(frm) {
if(r != 0)
{
frm.action = 'temp.jsp';
}else{
frm.action = 'temp2.jsp';
}
}
}
</script>

onsubmit check if checked and change source

this doesn't seem to work, and resets checked...would like to only update if checked
<iframe id="time" name="time" type="text/html" src="http://time.is/"></iframe>
<form id="url" onsubmit="" method="post">
<input type="text" name="target" id="target" value="http://time.is" size="40"></form>
<input type="checkbox" name="check1" />
$('.url').submit {
if($('input[name="check1"]', this).is(':checked')) {
document.getElementById(time).src = url;
} else {
alert('no');
}
return false;
});
http://jsfiddle.net/ZZe5X/57/
Because you put check box out side the form but in code you call if ($('input[name="check1"]', this).is(':checked')) { should move check box inside form and also remove onsubmit=""
<div class="c">
<iframe id="time" name="time" type="text/html" src="http://time.is/" frameborder="0" allowtransparency="true"></iframe>
</div>
<form id="url" method="post" target="time">
<div>
<input type="text" name="target" id="target" value="http://time.is" size="40">
<input type="checkbox" name="check1" />
</div>
</form>
<script>
$(function(){
$('#url').submit (function(){
if ($('input[name="check1"]', this).is(':checked')) {
document.getElementById('time').src = url;
} else {
alert('no');
}
return false;
});
});
</script>
http://jsfiddle.net/ZZe5X/66/
There are multiple errors:
1.you need to add submit button inside html form (or have a way to trigger form submission with JavaScript), something like this:
<input type="submit"/>
2.the varible url is undefined, you may add the following line in the JavaScript
var url = $('#target').val();
3.
document.getElementById(time).src = url;
should be
document.getElementById('time').src = url;
4.change the first line of script from
$('.url').submit {
to
$('#url').submit(function() {
5.as Trinh Hoang Nhu said, check box should be inside form because you are using
if ($('input[name="check1"]', this)...
Here's the updated test

Categories