I have searched and found answers for questions similar to mine, but I am not experienced with JS, so I am not sure how to apply the answers to my situation. I have a form where users enter a URL to submit to me. The URL can be from any site but when users enter a Youtube short (share) URL, I need the field to be changed to a regular Youtube URL before the form is submitted. Here are the two answers I have found to similar questions:
Change form values after submit button pressed
Automatically change a value in a form field
Basically, when a user enters URLS in this format:
https://youtu.be/VIDEO_ID_HERE
I need the text in the field changed to this format before the form is submitted:
https://www.youtube.com/watch?v=VIDEO_ID_HERE
Thank you for any help.
The code I have for this popup form is:
<!-- POPUP 8 // START -->
<div id="popup-8" class="container container-size-11 container-radius-1 container-padding-5 container-shadow-1 bg-color-1 position-relative responsive-popup">
<h3 class="title-2 title-border-bottom-1 color-1"><?php echo $this->_('Add an image from a website') ?></h3>
<form action="<?php echo $this->url(array('controller' => 'find-images'),'urlpin_c');?>" method="post" class="event-find-images">
<div class="form-1 form-margin-20 margin-top-20">
<div class="form-row">
<div class="notification notification-color-3"><?php echo $this->_('Check out our bookmarklet to make pinning from a website even easier!') ?></div>
</div>
<div class="form-row form-row-group-top form-row-group-top-padding-3 margin-top-20">
<span class="field-button field-button-position-1 fill">
<input name="url" type="text" placeholder="http://" class="field field-color-1 field-size-1 event-url-text">
<button type="submit" class="button button-type-1 button-color-2 button-size-3 event-loader"><?php echo $this->_('Find') ?></button>
</span>
</div>
<div class="form-row event-back-ios-8">
<div class="table-grid">
<div class="table-grid-cell event-upload-pin">
Back
</div>
</div>
</div>
<div class="hide notification notification-color-1 margin-top-20 event-url-status"></div>
<div class="form-row form-row-group-top form-row-group-top-padding-3 margin-top-20">
<ul class="list-30 clearfix hide event-found-images"></ul>
</div>
</div>
</form>
</div>
<!-- POPUP 8 // END -->
<script type="text/javascript">
$('.event-find-images').on('submit',function(){
App.addLoader('.event-loader');
$('.event-url-status').addClass('hide');
App._ajax({
url: '<?php echo $this->url(array('controller' => 'find-images'),'urlpin_c');?>',
onSuccess: function(json) {
App.removeLoader('.event-loader');
if(json.location) {
window.location = json.location;
} else if(json.errors) {
var errors = [];
for(i in json.errors)
errors.push(json.errors[i]);
$('.find-images').remove();
$('.event-url-status').html(errors.join("<br />")).removeClass("hide");
} else {
//console.log(json);
}
},
type: 'POST',
data: $(this).serialize()
});
return false;
});
</script>
You can check and change the input value when the user submit:
// When the user submits,
$('.event-find-images').on('submit',function(){
// Change value of the url.
$(".event-url-text").val(function(index, value) {
// Find for pattern and then replace.
return value.replace(
/https:\/\/youtu\.be\/(.+)/,
"https://www.youtube.com/watch?v=$1"
);
});
// the rest of your code...
Hope this helps!
Give you text box some id like
<input id="yturl" name="url" type="text" placeholder="http://" class="field field-color-1 field-size-1 event-url-text">
Add this in submit callback before you do App._ajax.Also see an example besides
var shorturl = $("#yturl").val(); // https://youtu.be/c8aFcHFu8QM
var urlarray = shorturl .split("/"); //["https:", "", "youtu.be", "c8aFcHFu8QM"]
var videoID = urlarray[3]; // c8aFcHFu8QM
$var = "https://www.youtube.com/watch?v="+videoID;
$("#yturl").val(fullurl ); // assign full url to text box
Now in ajax data: $(this).serialize() jquery would see and use this updated value
Related
my registration form has basic validation for html attributes, e.g. type = 'email' etc. They display nicely styled by the new feature in Bootstrap Validation.
The problem occurs when I send the form to PHP. First, the data goes through AJAX to PHP to display errors without refreshing the page, but when checking e.g. if the entered email is already registered with a negative result, my input is still marked as: valid (green highlight). What should I do
register.php
$success = false;
$error = false;
$mssg = "Error";
if(!isset($_POST['email']) && !isset($_POST['pass'])){
$mssg = "Inputs are empty";
}else{
//example result for database
$used_email = "foo#email.com";
// example validation
if($_POST['email'] == $used_email){
$error = 'email';
$mssg = "Email is already taken!";
}else $success=true;
}
header('Content-Type: application/json');
echo json_encode(array('success' => $success, 'error'=> $error, 'mssg' => $mssg));
exit;
(function (){
$("#formregister").on('submit', function(ev){
const form = $(this);
ev.preventDefault();
ev.stopPropagation();
var obj= new Object;
Object.keys(form[0].getElementsByTagName('input')).filter(function(key) {
obj[form[0][key].id] = form[0][key].value;
});
if (this.checkValidity()) {
$.ajax({
type: "POST",
url: "register.php",
data: obj,
cache: false,
success: function(data) {
if(!data.success) {
if(data.error){
$("#"+data.error).addClass("is-invalid").focus();
$("#"+data.error).next().html(data.mssg);
}else
$("#result").attr("class", "alert alert-danger").html(data.mssg);
}else{
$("#result").html("Success");
$("#result").attr("class", "alert alert-success");
}
}
});
}else form.find(":invalid").first().focus();
form.addClass("was-validated");
});
})();
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form class="needs-validation" id="formregister" novalidate>
<div id="result"></div>
<div class="mt-2">
<label for="email" class="form-label">E-mail</label>
<input type="email" class="form-control" id="email" required>
<div class="invalid-feedback">123</div>
</div>
<div class="mt-2">
<label for="pass" class="form-label">Password</label>
<input type="password" class="form-control" id="pass" required>
<div class="invalid-feedback"></div>
</div>
<div class="col-12 justify-content-end d-flex mt-4 mb-2">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</form>
</div>
If I add .is-invalid class during validation, input doesn't change its style to red.
Issue img
ON the STAYS GREEN issue:
After the server validation you have to change the class of the input with AJAX or PHP to .is-invalid to get the WRONG red style - or .is-valid for the correct value.
You can give the user additional hints with the .invalid-feedback is also supported with these classes.
Exampled can be found here:
https://getbootstrap.com/docs/5.0/forms/validation/#server-side
Formore help we need your PHP code
Update: you are using BS5 BETA.
THE V5.0 is now released.
Get it now and hopefully they fixed the bug.
https://getbootstrap.com/docs/5.0/getting-started/download/
I found the solution! The :invalid and :valid attributes have style advantages over classes, so the .is-invalid class must have border attributes with !imporant at the end.
For people who will have a similar problem in the future.
Need to add to boostrap.css .is-invalid and .is-valid -> !important
I've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.
Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.
<form id="selectform" th:object="${systemIdListForm}" th:action="#{/myController}" method="get">
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
$("#addMore").click(function() {
var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
$('#fields').append(html);
});
$("#selectform").submit(function(){
var values = $(this).serialize();
});
});
/*]]>*/
</script>
At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.
Any help is much appreciated
What data type have you used in Model ?
Make sure you have taken String [] for that field.
If not taken String [] then use that and let me know whether it works or not.
Also you can take help of below code.It is for your case only.
$("#selectform").submit(function (event) {
// form redirect stop
event.preventDefault();
var status = jbf.form.validate('#selectform');
if (!status) {
return;
}
// get form data
var data = {};
data["enrollmentNumber"] = $("#enrollmentNumber").val();
data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();
var url = "/yourURL";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
var message = response.message;
//success notification
if(response.success === true){
alert(message);
}else{
error(message);
}
},
error: function (e) {
console.log("ERROR: ", e);
error("Add failed");
}
});
});
I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.
<form id="selectform" th:object="${myEntiry}" th:action="#{/crops/singlecroplabeloffinsp/list/1}" method="get">
<input class="form-control" id="systemIdList" th:field="*{systemIds}" type="hidden"/>
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
...
$("#selectform").submit(function(){
//get all the system ids
var x = document.getElementsByName("systemIdInput");
var systemIds = [];
for (i = 0; i < x.length; i++ ) {
if (x[i].type ='text') {
systemIds.push(x[i].value);
}
}
$("#systemIdList").val(systemIds);
this.submit();
});
Added to the entity with getter & setter:
#Transient
private List<Integer> systemIds;
i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}
![enter image description here][1]
Here I have attached the screen shot and my question is, if I select a check box free form , I couldn't take free form inet commission and bo commission value alone.If I checked the check box, value is one means I should take value 1's inet and bo commissions. Please any one help me to solve the problem. Each check box have separate value like 1,2,etc.
Here is my code : I am working under codeigniter frame work. Here is the html code and I am fetching data from table.
Is there any possible solution to split values in jquery,
<?php
if(isset($service_list) && !empty($service_list))
{ ?>
<div class="form-group">
<label class="col-sm-3 control-label">Product Name</label>
<div class="col-sm-3" id="list_staff">
<input type="checkbox" name="check_all" class="chkSelectAll">(Click to Check all)
</div>
<div class="col-sm-2">
<label>I-net Commission</label>
</div>
<div class="col-sm-2">
<label>Bo Commission</label>
</div>
</div>
<?php
foreach($service_list as $val)
{
$ds=0;
if(isset($view_list) && !empty($view_list))
{
foreach($view_list as $val1)
{
if($val['id']==$val1['mas_pro_id'])
{
$ds=1;
}
}
}
?>
<div class="form-group">
<label class="col-sm-3 control-label"><?=$val['pro_name']?></label>
<div class="col-sm-3">
<input type="checkbox" class="check_all serve"
name="permission[<?=$val['id']?>]" value="<?=$val['id']?>" <?=($ds>0)?'checked':''?>>
</div>
<div class="col-sm-2">
<input type="text" class="int_com<?=$val['id']?>" id="inet" style="width:30px;"/>%
</div>
<div class="col-sm-2">
<input type="text" class="bo_com<?=$val['id']?>" id="bo" style="width:30px;" />%
</div>
</div>
<?php }
}
else
{
echo "<div align='center' style='margin-right:100px; color:red;'>Sorry No Data Found..!</div>";
}
?>
my script:
$('#submit').live('click',function()
{
for_loading('Loading Data Please Wait...');
var cat_id=$('.cat_id').val();
var s_cid=$('.u_sub_cat_id').val();
var chkId = '';
$('.serve:checked').each(function () {
chkId += $(this).val() + ",";
});
chkId = chkId.slice(0, -1);
$.ajax({
url:BASE_URL+"product/edit_ser",
type:'get',
data:{ cat_id:cat_id,s_cid:s_cid,chkId:chkId},
success:function(result){
$("#list_view").html(result);
//THIS IS FOR ALERT
<?php /*?>jQuery.gritter.add({
title: 'Success!',
text: 'Category Added Successfully.',
class_name: 'growl-success',
image: '<?=$theme_path?>/images/screen.png',
sticky: false,
time: ''
});<?php */?>
for_response('Data Updated Successfully...');
}
});
});
My Screen shot could be like this,
Product name A Commission B Commission
free form ck box 10 % 05%
bulk booking ck box 00 % 00%
I didn't clearly understood your question, But i suppose this you are trying to get the values of the text field when its corresponding checkbox is clicked, this too on submitting. So i have created a Fiddle.
Check here!
you have to give different id's to your html elements.
<input type="checkbox" class="check_all serve" name="permission" value="1" id="check_<?php echo $val['id']?>" />
and also
<input type="text" class="int_com_<?php echo $val['id']?> style inline" id="inet_<?php echo $val['id']?>" />
<input type="text" class="bo_com_<?php echo $val['id']?> style inline" id="bo_<?php echo $val['id']?>"/>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i made a login for my backend web page using jquery.
here is the form:
<form method="post" action="#" autocomplete='off'>
<h1 class="white-text">ADMIN Log in</h1>
<div class="row"><div id="errMsg"></div></div>
<div class="row">
<div class="large-12"><input type="text" placeholder="User ID" name="txtUsername" id="txtUsername"></div>
</div>
<div class="row">
<div class="large-12"><input type="password" placeholder="Password" name="txtPassword" id="txtPassword"></div>
</div>
<div class="row">
<div class="large-12 columns">
<p>Need Help Signing in?</p>
</div>
</div>
<div class="large-12 columns ">
<input type="submit" value="Sign In" class="button right" onclick="validLogin()">
</div>
</form>
here is the jQuery that handles the login:
function validLogin(){
var username=$('#txtUsername').val();
var password=$('#txtPassword').val();
var dataString = 'username='+ username + '&password='+ password;
$("#errMsg").hide();
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
if(result=='admin'){
window.location='admin.php';
}else if(result=='Invalid ID or password!') {
$("#errMsg").show(100);
$("#errMsg").html("LOGIN FAILED!: " + result);
}else{
$("#errMsg").fadeIn(100);
$("#errMsg").html(result);
}
}
});
}
and here is the php file from the url of the jquery:
<?php
session_start();
include('include/connection.php');
$message=array();
if(isset($_POST['username']) && !empty($_POST['username'])){
$username=$_POST['username'];
}else{
$message[]='<i class="foundicon-error"></i> username';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password=stripslashes($_POST['password']);
}else{
$message[]='<i class="foundicon-error"></i> password';
}
$countError=count($message);
if($countError > 0){
echo "Please enter your ";
for($i=0;$i<$countError;$i++){
if ($i > 0){
$con=" and ";
}else {
$con="";
}
echo $con.$message[$i];
}
}else{
$query="select * from admin_users where username='$username' and password='$password'";
$res = mysqli_query($connect,$query);
while($row = mysqli_fetch_assoc($res))
{
$userlvl = $row['user_level'];
}
$checkUser=mysqli_num_rows($res);
if($checkUser > 0){
$_SESSION['LOGIN_STATUS']=true;
$_SESSION['uname']=$username;
if ($userlvl == 1) {
echo 'admin';
}
else {
echo 'techadmin';
}
}else{
echo "Invalid ID or password!";
}
}
?>
i have no clue why do these codes doesn't work on firefox but it works flawlessly on chrome, IE, opera and safari..
it doesn't go to the page where it is intended to go... it just stays on the login page... no error returns or whatsoever... and also, there are no error logs in the console
function validLogin(){
event.preventDefault();
^
event is not defined, causes javascript abort.
also check a developer console, F12 key, or install a plugin FireBug for Firefox and see what console says.
EDIT
Are you sure that jQuery is enabled?
Can you post a jsfiddle for this case with full scenario?
Check console to see javascript errors, maybe you have parsing error somewhere, developer console will help.
EDIT2
change form
<form method="post" onsubmit="return validLogin();" action="#" autocomplete='off'>
.....
<div class="large-12 columns ">
<input type="submit" value="Sign In" class="button right">
</div>
</form>
and Js to:
function validLogin(){
var username=$('#tx....
.....
.....
return false; // at the end
}
jsfiddle: http://jsfiddle.net/9kcx9/
This should fix your problem. First give form an id:
<form method="post" action="#" autocomplete="off" id="myform">
<h1 class="white-text">ADMIN Log in</h1>
<div class="row"><div id="errMsg"></div></div>
<div class="row">
<div class="large-12"><input type="text" placeholder="User ID" name="txtUsername" id="txtUsername"></div>
</div>
<div class="row">
<div class="large-12"><input type="password" placeholder="Password" name="txtPassword" id="txtPassword"></div>
</div>
<div class="row">
<div class="large-12 columns">
<p>Need Help Signing in?</p>
</div>
</div>
<div class="large-12 columns ">
<input type="submit" value="Sign In" class="button right">
</div>
</form>
validLogin will have a Event passed, catch it using evt as parameter, using evt.preventDefault( ) and return false; (at the end) to prevent the default submit actions. Get your form element and set onsubmit=validLogin.
function validLogin(evt){
evt.preventDefault( );
var username=$('#txtUsername').val();
var password=$('#txtPassword').val();
var dataString = 'username='+ username + '&password='+ password;
$("#errMsg").hide();
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
if(result=='admin'){
window.location='admin.php';
}else if(result=='Invalid ID or password!') {
$("#errMsg").show(100);
$("#errMsg").html("LOGIN FAILED!: " + result);
}else{
$("#errMsg").fadeIn(100);
$("#errMsg").html(result);
}
}
});
return false;
}
document.getElementById("myform").onsubmit = validLogin;
tested here, works in firefox and chrome (open the jsbin console to see its working )