I have registration form on my website that, using jquery I append default values to, and onFocus/blur the default values hide and show accordingly.
My problem is that when the form is submitted and has kicked back errors using php validation, I am unable to show the posted values in the fields. The javascript seems to write over the posted data that is echoed using php in the input value.
When I look at the page source after posting my form I see that in the value of the input I do appear to have the posted value, the value that I want shown. Example:
<input type="text" name="first_name" value="Harry" />
PHP has done it's work in echoing the posted data into the value of my input. Then Javascript changes it so that instead of the user seeing their name (Harry in this example) they once again see the default jquery appended "First name".
This happens even though I have a value in the input.
How can I modify my Javascript to take note of the value of my input and not write over it?
This is the code so far:
$(document).ready(function() {
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
// cache references to the input elements into variables
var passwordField = $('input[name=password]');
var emailField = $('input[name=email_address]');
var firstnameField = $('input[name=first_name]');
var lastnameField = $('input[name=last_name]');
// get the default value for the fields
var emailFieldDefault = emailField.val();
var firstnameFieldDefault = firstnameField.val();
var lastnameFieldDefault = lastnameField.val();
// add a password placeholder field to the html
passwordField.after('<input id="passwordPlaceholder" type="text" value="Password" autocomplete="off" />');
var passwordPlaceholder = $('#passwordPlaceholder');
// show the placeholder with the prompt text and hide the actual password field
passwordPlaceholder.show();
passwordField.hide();
// when focus is placed on the placeholder hide the placeholder and show the actual password field
passwordPlaceholder.focus(function() {
passwordPlaceholder.hide();
passwordField.show();
passwordField.focus();
});
// and vice versa: hide the actual password field if no password has yet been entered
passwordField.blur(function() {
if(passwordField.val() == '') {
passwordPlaceholder.show();
passwordField.hide();
}
});
// when focus goes to and moves away from the fields, reset it to blank or restore the default depending if a value is entered
emailField.focus(function() {
if(emailField.val() == emailFieldDefault) {
emailField.val('');
}
});
emailField.blur(function() {
if(emailField.val() == '') {
emailField.val(emailFieldDefault);
}
});
firstnameField.focus(function() {
if(firstnameField.val() == firstnameFieldDefault) {
firstnameField.val('');
}
});
firstnameField.blur(function() {
if(firstnameField.val() == '') {
firstnameField.val(firstnameFieldDefault);
}
});
lastnameField.focus(function() {
if(lastnameField.val() == lastnameFieldDefault) {
lastnameField.val('');
}
});
lastnameField.blur(function() {
if(lastnameField.val() == '') {
lastnameField.val(lastnameFieldDefault);
}
});
});
$('input[name=first_name]').val('First name');
This unconditionally sets the value of that element to First Name. It's not a "only set the value if it's empty", it's "set the value to First Name, regardless of what it's in there".
You'd need something like this to preserve what's in there:
if ($('input[name=first_name]').val() == '') {
$('input[name=first_name]').val('First name');
}
instead, which would only reset the field's value if it starts out empty.
Just get some placeholder plugin, your code repeat itself too much and still does not do what you need
This is just what you need:
http://plugins.jquery.com/project/input-placeholder
With it your code will look very clear and simple, like:
<input type="text" name="first_name" placeholder="First Name" />
<input type="text" name="last_name" placeholder="Last Name" />
<input type="text" name="email_address" placeholder="Email" />
<script>
$(function(){
$('input[placeholder]').placeholder();
})
</script>
Instead all of your javascript
on ready function your are setting some values before your default values
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
so your defalut values cannot be empty
This is how i would do it so it would be more dynamic and less code.
<input type="text" name="first_name" rel="First Name" value="<?=$first_name?>" />
<input type="text" name="last_name" rel="Last Name" value="<?=$last_name?>" />
<input type="text" name="email" rel="Email" value="<?=$email?>" />
$(function(){
$('input').each(function(){
var val = $(this).val(),
rel = $(this).attr('rel');
$(this).focus(function(){
if(val === rel){
$(this).val('');
}
});
$(this).blur(function(){
if(val === ''){
$(this).val(rel);
}
});
if(val === ''){
$(this).val(rel);
}
});
});
With the minimum changes:
if($('input[name=first_name]').val()!='')
$('input[name=first_name]').val('First name');
if($('input[name=last_name]').val()!='')
$('input[name=last_name]').val('Last name');
if($('input[name=email_address]').val()!='')
$('input[name=email_address]').val('Email address');
Another cool way:
if($('input[name=first_name]').val()!='') {
$('input[name=first_name]').val('First name');
$('input[name=first_name]').class('init');
}
if($('input[name=last_name]').val()!='') {
$('input[name=last_name]').val('Last name');
$('input[name=last_name]').class('init');
}
if($('input[name=email_address]').val()!='') {
$('input[name=email_address]').val('Email address');
$('input[name=email_address]').class('init');
}
var initVals = new Array();
$("form input").each( function (i) { initVals[i] = this.value; } );
$("form input").focus( function () {
if ( $(this).hasClass("init") ){
$(this).removeClass("init");
$(this).val("");
}
} );
$("form input").blur( function (i) {
if ( $(this).val() == "" || $(this).val() == initVals[$("form input").index(this)] ){
$(this).addClass("init");
$(this).val( initVals[$("form input").index(this)] );
};
} );
Don't forget to use hasClass("init") or similar to avoid sending inputs with its default value.
Related
I want to take the value from text field to a variable for checking a condition
Is it possible in view? I'm using CodeIgniter.
<input type="text" id="student_gen" name="student_gen">
On form submit you can take value in javascript function like:-
var x=document.getElementbyId('student_gen').value;
If you want to do it on entering text immediately then you can call a function on onchange="myFunction()"
and in function you can take value by above method.
In action form set current_url() after submit get input in this way
$this->input->post('student_gen');
if (!$this->input->post('student_gen'))
echo 'empty field';
elseif ($this->input->post('student_gen') != 'M')
echo 'wrong value';
or You can get and check with jquery
$('#student_gen').change(function(){
if (!$(this).val() || $(this).val() != 'M')
alert('Wrong or empty value');
});
You can use jQuery:
$(document).ready(function(){
$("#student_gen").change(function(){
var x = $("#student_gen").val();
if(x=='condition'){
code..
}
});
});
or javaScript:
<script>
function myFunction() {
var x = document.getElementById("student_gen").value;
if(x=='condition'){
code..
}
}
</script>
<input type="text" id="student_gen" name="student_gen" onchange="myFunction()">
I have a simple php and jquery contact form (3 fields: name - email - message), whose input field are coded like this:
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField"/>
I'd like those field to have a default value, rather than being empty. At the same time i wouldn't trust using the placeholder attribute, since it is not universally supported.
I found this jquery script that does the job in an excellent way:
<script>
$(function() {
$( ".contact_form_field" )
.focus(function() {
var $this = $(this);
if (!$this.data('default')) {
$this.data('default', $this.val());
}
if ($this.val() == $this.data('default')) {
$this.val('')
.css('color', '#000');
}
})
.blur(function() {
var $this = $(this);
if ($this.val() == '') {
$(this).val($this.data('default'))
.css('color', '#666');
}
})
.css('color', '#666')
});
</script>
However, to make it work i had to change the value attributes of the field to the desidered placeholder text:
<input type="text" name="contactName" id="contactName" value="Name" class="requiredField"/>
This, predictably, seems to interfere with the form action that should prevent the mail being sent if there are empty fields:
if(trim($_POST['contactName']) === '') {
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
I thought i just had to change the string to
if(trim($_POST['contactName']) === 'Name') { or
if(trim($_POST['contactName']) == 'Name') { or
but it doesn't seem to work. The mail gets sent even if the field is left untouched (not empty, since the "Name" text is displayed).
I am at a loss to understand what i'm doing wrong, any input (sorry for the pun x_x) would be greatly appreciated.
Placeholders are quite ready to use today. But if you still don't trust it you can use old solution based on onfocus and onblur attributes. Here's an example:
<input onfocus="if(this.value==='default value') this.value=''" onblur="if(this.value==='') this.value='default value'">
create an array with all the default values and test to see if the submitted value is part of the default value
$defaultValue = array('', 'Name');
if(in_array(trim($_POST['contactName']), $defaultValue) {
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
I'm trying to validate a form using Ajax and onchange function. Basically I want automatic validation once the focus is gone from the input box. Then it will state an error if it's blank / invalid entry.
For some reason the validation works for invalid entries but won't work for empty inputs on first try (meaning if i refresh page and go to second field box by tab, there's no error). The funny thing is the empty error works fine after i erase an entry. I've tried using $var = "" or empty($var) but I still get the same results.
Here's the php part:
if(isset($_GET["isbn"]) )
{
$isbn = $_GET["isbn"];
$error="";
if(empty($isbn) || !preg_match("/^\d{12}$/", $isbn) )
{
$error .= "Please enter a valid ISBN";
echo $error;
}
else
echo $error;
}
Here's the rest:
<script type="text/javascript">
function validateIsbn(keyword)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.status == 200 && xhr.readyState == 4)
{
var res = xhr.responseText;
document.getElementById("err1").innerHTML = res;
}
}
xhr.open("get","validate_isbn.php?isbn=" + keyword,true);
xhr.send();
}
</script>
<form method="get" action="">
<label class="top-label">ISBN:</label>
<input name="isbn" id="isbn" type="text" onchange="validateIsbn(this.value)"/>
<div id="err1"> </div>
<p></p><p></p>
You say you want automatic validation once the focus is gone from the input box. The event triggered in that case is onblur, not onchange.
What I'm trying to get is to count which checkboxes in article list are selected, and I'm writing selected to "toDel" jquery variable.
Then, if "toDel" remains empty, I'd like to stop submiting the form, and if there is any, I'm proceeding by adding "toDel" value to hidden field value.
If selected it all works fine, but once if I click button and no chechboxes are selected, "return false" somehow stops, and I when new checkbox is selected, I can't get into "correct" part of the code.
I've checked here, and figured out that I can't use "return false" so I tried with validator variable, but it behaves the same.
$(document).ready(function(){
$("#jqdeleteselected").on("click", function(){
var toDel='';
$('.jqchkbx').each(function() {
if ($(this).attr('checked')) {
toDel += ($(this).attr('value')+',')
}
});
console.log(toDel);
$("#send").submit(function() {
var valid = true;
if (toDel != '') {
$('#boxevi').val(toDel);
console.log('filled');
}
console.log('empty');
valid = false;
});
return valid;
});
});
<form method="POST" action='.$_SERVER['REQUEST_URI'].' name="send" id="send">
<input type="hidden" id="boxevi" name="boxevi" />
<input type="submit" id="jqdeleteselected" value="Obriši označene">
<input type="submit" name="addnew" value="Dodaj novi artikl" /></form><br /></div>';
You only need to handle submit event:
$(document).ready(function(){
$("#send").submit(function() {
var toDel='';
$('.jqchkbx').each(function() {
if ($(this).attr('checked')) {
toDel += ($(this).attr('value')+',')
}
});
console.log(toDel);
if (toDel != '') {
$('#boxevi').val(toDel);
console.log('filled');
}else{
console.log('empty');
return false;
}
});
});
You only need to handle submit and you can use :checked selector to speed up your check
$(document).ready(function(){
$("#send").submit(function() {
var toDel='',
$this = $(this),
checkd = $(".jqchkbx:checked");
checkd.each(function() {
toDel += $(this).val() + ',';
});
console.log(toDel);
if (checkd.length > 0) {
$('#boxevi').val(toDel);
console.log('filled');
}else{
console.log('empty');
return false;
}
});
});
as a follow up to this question, while the checkbox value is stored on pageload, the text is displayed on pageload, even if the checkbox is unchecked. the text should hide/display only if the user has unchecked/checked the checkbox, throughout the session or till he closes the browser.
js code which stores the checkbox state:
function getStorage(key_prefix) {
// this function will return us an object with a "set" and "get" method
// using either localStorage if available, or defaulting to document.cookie
if (window.localStorage) {
// use localStorage:
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
// use document.cookie:
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = decodeURIComponent(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
// a key prefix is used for the cookie/storage
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
$('#ab_'+this.id).toggle($(this).is(':checked'));
// save the data on change
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
// on load, set the value to what we read from storage:
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val) $(this).trigger('change');
});
});
this ^code should work, but it while it retains the state of the checkbox, it doesn't for the text. is it because the text is being called from a php page?
html:
$(document).ready(function() {
$("#bquote").load("quotes_in.php");
});
.. ...
<div class="check">
<p><input type="checkbox" value="Name" id="name" checked /> <label for="name">Name</label></p>
<p><input type="checkbox" value="Reference " id="reference" checked /> <label for="reference">Reference</label></p>
</div>
.. ...
<blockquote id="bquote">
</blockquote>
php:
public function formatQuotes($row)
{
return "<p id=\"ab_name\">" . $this->h($row['cName']) . "</p><br />"
. "<p id=\"ab_reference\">" . $this->h($row['vReference']) . "</p>";
}
You need to trigger the change() event on document ready after the p elements are generated.
Edit:
If placing the change trigger after the .load() call does not work, then that is probably due to the ajax request not being completed yet at the point of triggering. This can be solved by using callback parameter of .load(). Therefore, the code should look something like:
$(document).ready(function() {
$("#bquote").load("quotes_in.php", function() {
// create the P elements
// trigger the change() event
});
});