How to conditionally enable or disable to editable field (edit/read only)? I used session role from database to make condition on the text field. However, I don't know how to proceed it...
<?php
include('session.php');
?>
<tr class="row1">
<td width="30%"><div align="left">Customer name1</div></td>
<td width="100%">
<div align="left">
<input type="text" name="CMCNA1" id="CMCNA1" style="width:100%;" pattern="[A-Za-z]+" title="Please insert alphabetical only" maxlength="35"/>
</div>
</td>
I know it's an old post, but just in case, for those who have this needs.
Base on the code of Narayan, maybe by doing this (with jquery):
<script type="text/javascript" >
function makerCheckerField()
{
var role= <?php echo $_SESSION['login_user_role']; ?>;
var maker='Maker';
if (role === maker){
$('#CMCNA1').attr('readonly', 'readonly');
} else {
$('#CMCNA1').removeAttr('readonly');
}
}
</script>
If I am not wrong the readonly property works like this :
readonly = "readonly" or "" (empty string) or empty
Specifies that element represents a control whose value is not meant to be edited.
Maybe you will have to manage correctly the differents states of roles (what happens if you came back to the default state etc...).
You can also play with
.setAttribute, .getAttribute and .removeAttribute
I don't know if this is what you was looking for.
Try this -->>
<script type="text/javascript" >
function makerCheckerField()
{
var role= <?php echo $_SESSION['login_user_role']; ?>;
var maker="Maker";
if (role === maker) // equal value and equal type
{
$("#CMCNA2").attr("readonly", true);
} else {$("#CMCNA2").attr("readonly", false);}
}
</script>
you can add attribut readonly="true" to make the input readonly/not editable:
<input type="text" name="CMCNA1" id="CMCNA1" style="width:100%;" pattern="[A-Za-z]+" title="Please insert alphabetical only" maxlength="35" readonly="true" />
Related
I wrote several functions to check if the two passwords are equal. When I click out of the "verify password" box, it should either display "The passwords match" or "Please enter your password again because the two passwords don't match" depending on whether or not the passwords are equal to each other. However, when I type in two identical or two different passwords and I click out of the "verify password" text box, the message is not displayed at all. What am I doing wrong here?
This is what the assignment is asking:
The webpage should have two input boxes of type="password". The user will need to enter a new password in the first input box, then type the password again in the second input box.
When focus leaves the second box, your script checks to make sure the values of both boxes are the same and not empty (5 points). Note: A lot of examples on the Internet use the html input onchange property in the html file to call the event handler. Do not use any html property of of any type to handle events. Instead, define an event listener in your .js file (5 points).
If they're not the same, display a message saying that a second try is needed and reset the focus in the first password box.
If they are the same, replace any previous error messages with a message saying the passwords match.
I am using a password.js file and a setpassword.html file for this webpage.
My password.js file is:
var password1 = document.getElementById("txtPassword").value;
var verifypassword = document.getElementById("txtPWVerified").value;
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
if(password1 == verifypassword && password1 != "" && verifypasword != "") {
alert('The passwords match');
}
else if(password1 != verifypassword || password1 == "" || verifypasword == "") {
alert("Please enter your password again because the two passwords don't match");
}
}
verifypasswordclick.onblur = function() {
verifypassword1;
};
My setpassword.html file is:
<!DOCTYPE html>
<!-- H5FormValidation.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Register Here</title>
</head>
<body>
<h2>Register Here</h2>
<form id="formTest" method="get" action="processData">
<table>
<tr>
<td><label for="txtEmail">Email<span class="required">*</span></label></td>
<td><input type="email" id="txtEmail" name="email" required></td>
</tr>
<tr>
<td><label for="txtPassword">Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPassword" name="password" required></td>
</tr>
<tr>
<td><label for="txtPWVerified">Verify Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPWVerified" name="pwVerified" required></td>
</tr>
<tr>
<td> </td>
<td>
<input type="reset" value="CLEAR" id="btnReset"></td>
</tr>
</table>
</form>
<script src = "password.js"></script>
</body>
</html>
Instead of this
verifypasswordclick.onblur = function() { verifypassword1;}
Do this
verifypasswordclick.onblur = verifypassword1;
You're not calling the verifypassword1 function correctly. You need parentheses. But instead of calling the function from within an anonymous function, you can try this line instead.
verifypasswordclick.addEventListener("blur",verifypassword1);
Also, you're comparing the initial values every time. You need to get the new values from the input elements each time you check the passwords. In your verifypassword1 function, you need to get the new value from those input elements like so.
function verifypassword1() {
password1 = document.getElementById("txtPassword").value;
verifypassword = document.getElementById("txtPWVerified").value;
// rest of code
}
On my site I have a main search (powered by Google, placed throughout the site) and I have now created a second search (on its own page, which searches my DB for images based on user input text) which is a totally separate search to the google one.
What I want to do -
I want both Search forms to share a single text input field, but allow the user to choose which search to use (Google or Images Only) via radiobutton.
So we'd have:
[search input field][go] (o)Use Google (o)Image Search only
I'm no coder but can hack enough to just about get by, it just takes me a day or two to figure out and get working.
What I need and would save me a great deal of time, as I'm stumped on how to proceed with this or if it is even possible! If someone could tell me A) If it's possible, and B) A few pointers if it is. For instance I'm guessing it will probably need a bit of JavaScript to make it possible?
Any pointers would be appreciated, then I can see what I can do.
All the best,
Chris
// My Stand-alone Image Search Page ////////////////////////////////
<form method="post" action="imagesearch?go" id="search-form">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
// code for above form //
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
$sql="SELECT ID FROM ImageTable WHERE Name LIKE '%" . $name . "%' Order by Date Desc LIMIT 50";
//-run the query against the mysql query function
$result=mysql_query($sql);
// Create while loop and loop through result set//
$content .= ' <p><div id="wrapper">';
while($row=mysql_fetch_array($result)){
$id=$row['ID'];
$img = new Image($id);
// Format results//
$content .= '<div id="imgrt"><img src="/img/M/'.$img->ID.'.jpg" class="searchimg"><br>'.$img->Name.'';
$content .= '</div>';
}
$content .= '';$content .= '</div>';
}
else{
$content .= ' <p>Please enter a search query</p>';
}
}
}
// End of Stand-alone image search page /////////////////////////
---------------------------------------------------------------------------
// My sites main Google powered Search
<form action="http://www.example.com/gsresults" id="cse-search-box" class="searchmain">
<input type="hidden" name="cx" value="partner-pub-XXXXXXXXXXXXXXX" />
<input type="hidden" name="cof" value="FORID:XX" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="mainsearch">
<input type="submit" name="sa" value="Go" class="mainsearchbutton"/>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang="></script>
OK so here we go. If you plonk this in an empty html file you can see it in action (Tried to make a jsfiddle but didnt work for some reason). What this does is set an "active" id on the selected combo option, and when you click the submit button it grabs the value of the combo option with that id, and goes to the page of that value. so if you click google and then the button you go to google.html, and same goes for image, image.html. If you want some more specifics you can ask, but thats the main logic there.
<script>
function replaceActive(obj) {
var activeElm = document.getElementById("active");
activeElm.id = activeElm.id.replace("active", "");
obj.id = "active";
}
function formFunction(obj) {
obj.action = document.getElementById("active").value + ".html";
}
</script>
<form action="#" onsubmit="return formFunction(this);" method="post">
<input type="text" />
<select>
<option value="google" id="active" onclick="replaceActive(this);">Google</option>
<option value="image" onclick="replaceActive(this);">Images</option>
</select>
<input type="submit" />
</form>
Basically you can change that "formFunction()" function's code and and use "document.getElementById("active").value" to do what ever you wanted to do.
we have list employees with email id using below code
<tbody>
<?php
$sqlquery = mysql_query("select * FROM employee");
while($row=mysql_fetch_object($sqlquery)){
?>
<tr class="gradeA">
<td><input type="checkbox" name="eid" value="<?php echo $row->emailid;?>" onclick="send_email_form_test()"><?php echo $row->name;?></td>
</tr>
<?php }?>
</tbody>
when checkbox is clicked following function call,
function send_email_form_test(){
var selected = new Array();
$("input:checkbox[name=eid]:checked").each(function() {
if($(this).val() !=""){
selected.push($(this).val());
}
});
alert(selected.join(','));
var final_email = selected.join(',');
document.getElementById("to").value =final_email;
}
after click the checkbox,email ids are appears in "to" textarea field .when i will go to second page of the employee list, i cant able to get "to" textarea field,it will empty on the second page
<div>
<label for="required">TO</label>
<textarea name="to" cols="5" rows="10"></textarea>
</div>
<div>
<label for="email">Subject</label>
<input type="text" size="80" id="subject" name="subject" >
<input type="submit" name="submit" value="submit">
</div>
how to add and remove the email ids with comma separated,when i click the checkbox.I have issue on when i will go on next page of the pagination
You can add 'this' parameter to the Javascript function as onclick="send_email_form_test(this)"> then you will get the clicked checkbox object. Then you will be able to retrieve the value of the clicked check box
I did not test it, but I think this is how you could collect emails from all pages
<?php
//...
echo '<script>window.tablePage = ', $paginator->currentPage, ';</script>';
?>
<script type="application/javascript">
//...
pageSelected = selected.join(',');
//get emails selected on other pages
allSelected = JSON.parse(localStorage.getItem('emails'));
//add currently selected emails
allSelected[tablePage] = pageSelected;
localStorage.setItem('emails', JSON.stringify(allSelected));
//output emails from all pages
document.getElementById("to").value = allSelected.join(',');
//...
</script>
(JSON library is here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js )
Can I reload current page without losing any form data? I used..
window.location = window.location.href;
and
window.location.reload(true);
But these two things can't get earlier form datas for me. What is wrong ? When refresh browser manually, it is fine (I don't lose any form data). Please guide me how to figure it out.
Here is my full code...
<div class="form-actions">
<form>
<table cellpadding = "5" cellspacing ="10">
<tr class="control-group">
<td style="width: 100px;">
<div>Name: <font color="red">(*)</font></div>
</td>
<td>
<input type="text" id="inputName" placeholder="Name" required>
</td>
</tr>
<tr class="control-group">
<td>
<div>Email: <font color="red">(*)</font></div>
</td>
<td>
<input class="span3" placeholder="user#gmail.com" id= "inputEmail" type="email" required>
</td>
</tr>
<tr class="control-group">
<td>
<div>Phone: </div>
</td>
<td>
<input type="text" id="inputPhone" placeholder="phone number">
</td>
</tr>
<tr class="control-group">
<td>
<div>Subject: <font color="red">(*)</font></div>
</td>
<td>
<input type="text" id="inputSubject" placeholder="Subject" required>
</td>
</tr>
<tr class="control-group">
<td colspan ="2">
<div>
<div>Detail: </div>
<div class="controls">
<textarea id="inputDetail"></textarea>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div>
<label style="font-weight: bold;" class="checkbox"> <input id="confirmCheck" value="" type="checkbox">
I Agree to the Personal information handling policy
</label>
</div>
<div id = "alert_placeholder"></div>
<div class="acceptment">
[Personal information handling policy]<br> <br>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<button id="btnConfirm" class="btn btn-primary">Confirm</button>
<input type="reset" style="width: 65px; height: 27px;" id="btnReset" class="btn">
</div>
</td>
</tr>
</table>
</form>
</div>
And at my JS file..
function bind() {
$('#btnConfirm').click(function(e) {
if ($('#confirmCheck').is(":checked")) {
getConfirmationForSendFAQ();
}
else {
e.preventDefault();
showalert("You should accept \"Personal Information Policy\" !", "alert-error");
}
});};function getConfirmationForSendFAQ() {
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var phone = $('#inputPhone').val();
var subject = $('#inputSubject').val();
var detail = $('#inputDetail').val();
$('.form-actions').empty();
html = [];
html.push("<table cellpadding ='8' class = 'submitInfo'");
html.push("<tr>");
html.push("<td class = 'title'>Name:</div>");
html.push("<td class = 'value'>"+ name +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td class = 'title'>Email Address:</div>");
html.push("<td class = 'value'>"+ email +"</td>");
html.push("</tr>");
if (phone.trim().length > 0) {
html.push("<tr>");
html.push("<td class = 'title'>Phone No:</div>");
html.push("<td class = 'value'>"+ phone +"</td>");
html.push("</tr>");
}
html.push("<tr>");
html.push("<td class = 'title'>Subject:</div>");
html.push("<td class = 'value'>"+ subject +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td class = 'title'>Detail Info:</div>");
html.push("<td class = 'value'>"+ detail +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td colspan='2'><div align = 'center'>");
html.push("<button id='btnSend' class='btn btn-primary' style='width: 65px;'>Send</button>");
html.push("<button id='btnReturn' class='btn btn-inverse' style='width: 65px; height: 27px; margin-left: 5px;'>Return</button>");
html.push("</div></td></tr>");
html.push("</table>");
$('.form-actions').append(html.join(''));
$('#btnReturn').click(function(e) {
// HERE I WANT TO KNOW HOW TO DO.....
});
$('#btnSend').click(function(e) {
alert("Doom");
});}
You can use various local storage mechanisms to store this data in the browser such as the Web Storage API, IndexedDB and WebSQL (deprecated) (and UserData with IE).
The simplest and most widely supported is Web Storage where you have persistent storage (localStorage) or session based (sessionStorage) which is in memory until you close the browser. Both share the same API.
You can for example (simplified) do something like this when the page is about to reload:
window.onbeforeunload = function() {
localStorage.setItem("name", $('#inputName').val());
localStorage.setItem("email", $('#inputEmail').val());
localStorage.setItem("phone", $('#inputPhone').val());
localStorage.setItem("subject", $('#inputSubject').val());
localStorage.setItem("detail", $('#inputDetail').val());
// ...
}
Web Storage works synchronously so this may work here. Optionally you can store the data for each blur event on the elements where the data is entered.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem("name");
if (name !== null) $('#inputName').val("name");
// ...
}
getItem returns null if the data does not exist.
Replace "localStorage" with "sessionStorage" in the code above if you want to store data only temporary.
I modified K3N's code to work for my purpose, and I added some comments to help others figure out how sessionStorage works.
<script>
// Run on page load
window.onload = function() {
// If sessionStorage is storing default values (ex. name), exit the function and do not restore data
if (sessionStorage.getItem('name') == "name") {
return;
}
// If values are not blank, restore them to the fields
var name = sessionStorage.getItem('name');
if (name !== null) $('#inputName').val(name);
var email = sessionStorage.getItem('email');
if (email !== null) $('#inputEmail').val(email);
var subject= sessionStorage.getItem('subject');
if (subject!== null) $('#inputSubject').val(subject);
var message= sessionStorage.getItem('message');
if (message!== null) $('#inputMessage').val(message);
}
// Before refreshing the page, save the form data to sessionStorage
window.onbeforeunload = function() {
sessionStorage.setItem("name", $('#inputName').val());
sessionStorage.setItem("email", $('#inputEmail').val());
sessionStorage.setItem("subject", $('#inputSubject').val());
sessionStorage.setItem("message", $('#inputMessage').val());
}
</script>
Find this on GitHub. Specially created for it.
https://gist.github.com/zaus/4717416
This answer was extremely helpful to me, and saves the trouble of going through each field manually:
Using jQuery to store the state of a complicated form
window.location.reload() // without passing true as argument
works for me.
As some answers mention, localStorage is a good option and you can certainly do it yourself, but if you're looking for a polished option, there is already a project on GitHub that does this called garlic.js.
I usually submit automatically my own form to the server and reload the page with filled arguments. Replace the placeholder arguments with the params your server received.
Agree with HTML5 LocaStorage.
This is example code
You have to submit data and reload page (server side render form with data), just reloading will not preserve data. It is just your browser might be caching form data on manual refresh (not same across browsers).
You can use localStorage ( http://www.w3schools.com/html/html5_webstorage.asp ) to save values before refreshing the page.
You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)
The optional second parameter of each FormPersistence function defines whether to use local storage (false) or session storage (true). In your case, session storage is likely more appropriate.
The form data by default will be cleared from storage upon submission, unless you pass false as the third parameter. If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter. See the repository for complete documentation.
A simple and generic (no jquery) solution for all input (type text) fields unsing the local storage.
function save_data(){
let fields = document.querySelectorAll("input[type='text']")
let saved_fields = []
fields.forEach(x => {
saved_fields.push({
key: x.id,
value: x.value
})
})
localStorage.setItem("saved_data", JSON.stringify(saved_fields))
}
function show_saved_data(){
JSON.parse(localStorage.getItem("saved_data")).forEach(x => {
document.getElementById(x.key).value = x.value
})
}
if you want to include "select/checkboxes" fields etc. you would have to add some if else logic in the for loop and change the query....
Use $_POST itself:
<?php
isset($_POST['value']) ? $value= $_POST['value'] : $value= NULL;
echo '<form method="POST">';
echo '<input type="text" name="value" value="'.$value.'"/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
?>
Register an event listener for keyup event:
document.getElementById("input").addEventListener("keyup", function(e){
var someVarName = input.value;
sessionStorage.setItem("someVarKey", someVarName);
input.value = sessionStorage.getItem("someVarKey");
});
I am having problem printing a particular variable from my cgi file. I receive this variable, called totalCost from my webpage and then try to print it, but nothing happens. All the other variables can be received successfully from the webpage and printed out on another webpage via my cgi file, except for this one..i've checked for case sensitivity but that didnt help
The code in html...
<tr> <td colspan=3 padding=2><b> Total = $ </b> <input type= "text" id="totalCost" disabled= true name= "totalCost" size ="5" maxlength="5" value= 0.00 /> <td> <tr>
the computeCost function
<script type= "text/javascript">
function computeCost(){
var apples= document.getElementById("appleQty").value;
var oranges=document.getElementById("orangeQty").value;
var bananas=document.getElementById("bananaQty").value;
var totCostTemp=0.69*apples + 0.59*oranges + 0.39*bananas;
document.getElementById("totalCost").value= totCostTemp;
}
</script>
In cgi file, which I write using Perl, I receive my variable in this manner:
my ($appleQty, $orangeQty, $bananaQty, $user, $cardType, $c) = (param("appleQty"), param("orangeQty"), param("bananaQty"), param("user"), param("cardType"), param("totalCost"));
then try to print out in this manner..
print header;
print start_html("Receipt"),
print h3("Fruit Store: Order Summary"),
table({-border => 2} ,caption("Your Receipt"),
Tr([th("Name:").td($user),th("Payment Method:").td($cardType),th("Fruit Type").td("Quantity"), th("Apple").td($appleQty), th("Oranges").td($orangeQty), th("Bananas").td($bananaQty), th("Total Cost:").td($c)]));
print end_html;
Please note...all variables except totalCost get printed correctly. totalCost is not printed at all in my resultant webpage...I think this has to do with the fact that I did some computation and perhaps did not store it properly in the id. But I dont know how to resolve that..
thank you for advising!
Disabled fields don't get posted. So you simply need to modify the field to make it readonly. Like :
<input type="text" id="totalCost" readonly="true" name="totalCost" size ="5" value="0.00" />
If you don't like the color of the readonly field, you can use a CSS to modify it like :
<style>
input[readonly=true] {
color:silver;
}
</style>
Or for better CSS compatibility :
<style>
.disabled {
color:silver;
}
</style>
<input type="text" id="totalCost" readonly="true" name="totalCost" size ="5" value="0.00" class="disabled" />
You may also use hidden fields, but you don't have to change your current code.
If the <input> element is never enabled, then it will not be sent to the server when the form is posted.
If you don't want the user to be able to update the field, then don't use an ordinary "text" <input>. Put a <span> there to hold the value, and update an enabled "hidden" <input> instead.
function computeCost(){
var apples= document.getElementById("appleQty").value;
var oranges=document.getElementById("orangeQty").value;
var bananas=document.getElementById("bananaQty").value;
var totCostTemp=0.69*apples + 0.59*oranges + 0.39*bananas;
document.getElementById("totalCost").value= totCostTemp;
document.getElementById('totalCostView').innerHTML = '$' + totCostTemp;
}
and the page would look like:
<td>
<span id='totalCostView'>$0.00</span>
<input type='hidden' id='totalCost' name='totalCost' value='0.00'>
</td>