I have a form form that either has input/select fields in form when account status is active, in this state you are able to add/edit user info, in another state Frozen, I would use the same view but replace the input and select fields with paragraph tags <p class="form-control-static"> for read-only purpose. I am populating the field when entering to EDIT mode with jQuery:
function fillFormFromObject(form, obj) {
form.find("input, select").each(
function (i, el) {
console.log(el);
$(el).val(obj[el.name]);
}
);
}
Now in paragraph case, how can I set the text for it from the object as well? Getting lost in here. I know that for paragraph element I would call text() method. But what would I pass in?
This is a proposal for a partial Answer. It includes some of the desired features, and doesn't include some others (which probably could be worked out with some experimenting).
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>test-page</title>
<script type="text/javascript">
//<!--
var f="i";
function inpdisp()
{ var d, i, x
for(x=0; x<4; x++)
{ if(x<10) //HTML code is ready for up to 100 input-fields/spans
i="0"+x;
else
i=x.toString();
d=document.getElementById("i"+i);
d.hidden = (f=="i" ? true : false);
// d.value="new value"+i; //uncomment when filling data from Server
d=document.getElementById("s"+i);
d.hidden = (f=="i" ? false : true);
// d.innerHTML="new value"+i+","; //uncomment when filling data from Server
}
f = (f=="i" ? "s" : "i");
return;
}
// -->
</script>
</head>
<body onload="inpdisp();">
<input type="button" value="inputs/displays" onclick="inpdisp();" />
<p><input id="i00" type="text" size="20" maxlength="30" value="data00" /><span id="s00">data00,</span> Type of data 00</p>
<p><input id="i01" type="text" size="20" maxlength="30" value="data01" /><span id="s01">data01,</span> Type of data 01</p>
<p><input id="i02" type="text" size="20" maxlength="30" value="data02" /><span id="s02">data02,</span> Type of data 02</p>
<p><input id="i03" type="text" size="20" maxlength="30" value="data03" /><span id="s03">data03,</span> Type of data 03</p>
</body>
</html>
That inpdisp() function is tied to a button only for "show" here. You would eliminate the button and call the function using some other criteria, in your version of this page. You will probably NOT want to modify the f variable inside the inpdisp() function, but do it elsewhere.
Related
I'm doing an exercise but I can't validate and send a form.
I have this HTML code, to which I cannot add or modify anything:
</head>
<body>
<h1>Card game</h1>
<p>
<label>Displays the name of the participant</label
><input type="text" name="name" />
</p>
<p>
<label>how many games do you want to play? </ tag
><input type="number" name="games" value="0" />
</p>
<button>PARTICIPATE!</button>
<script type="text/javascript" src="rockPaperScissors.js"></script>
</body>
I am trying to validate the form, which should turn the fields red when I hit the participate button and does not meet the validation conditions. Once the data has been corrected and the form has been validated, the fields must be deactivated so that they cannot be written again and remain visual.
I have done this but I don't get my goal:
function validateName() {
const name = document.getElementsByName("name");
const expression1 = /[A-Za-z]{3,}/;
name.click();
if (!expression1.test(name.value)) {
name.classList.add("RedBackground");
false return;
}
return true;
}
function validateGames() {
games.click();
const items = document.getElementsByName("items");
if (games.value <= 0) {
games.classList.add("RedBackground");
false return;
}
return true;
}
// Indicate who launches the events
document
.getElementsByTagName("button")[0]
.addEventListener("click", validateName);
document
.getElementsByTagName("button")[0]
.addEventListener("click", validateGames);
Issue
<input type="text" name="name" />
const name = document.getElementsByName("name");
getElementsByName returns a collection and not a single element.
Possible solution
To get the first element whose name attribute equals name, you have to either get the first index of the collection:
const name = document.getElementsByName("name")[0];
or querySelector which returns the first matching element.
const name = document.querySelector("[name=name]");
Example
document.querySelector("button").addEventListener("click", function(){
//REM: Is everything valid?
let tValid = true;
//REM: Validate "name" using "querySelector"
let tName = document.querySelector("[name=name]");
if(tName){
//REM: Put your logic here
tName.classList.add("RedBackground");
tValid = false
};
//REM: Validate "games" using "getElementsByName"
let tGames = document.getElementsByName("games")[0];
if(tGames){
//REM: Put your logic here
tGames.classList.add("BlueBackground");
tValid = false
};
return tValid
});
.RedBackground{
background-color: crimson
}
.BlueBackground{
background-color: cornflowerblue
}
<h1>Card game</h1>
<p>
<label>Displays the name of the participant</label>
<input type="text" name="name" />
</p>
<p>
<label>how many games do you want to play? </ tag>
<input type="number" name="games" value="0" />
</p>
<button>PARTICIPATE!</button>
I recommend, even if possible, not to reuse the keyword name as variable name.
How do I identify empty textboxes using jQuery? I would like to do it using selectors if it is at all possible. Also, I must select on id since in the real code where I want to use this I don't want to select all text inputs.
In my following two code examples the first one accurately displays the value typed into the textbox "txt2" by the user. The second example identifies that there is an empty textbox, but if you fill it in it still regards it as empty. Why is this?
Can this be done using just selectors?
This code reports the value in textbox "txt2":
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#cmdSubmit').click(function() {
alert($('[id=txt2]').val());
});
});
</script>
</head>
<body>
<form>
<input type="text" name="txt1" id="txt1" value="123" /><br />
<input type="text" name="txt2" id="txt2" value="" /><br />
<input type="text" name="txt3" id="txt3" value="abc" /><br />
<input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
</form>
</body>
</html>
This code always reports textbox "txt2" as empty:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#cmdSubmit').click(function() {
if($('[id^=txt][value=""]').length > 0) {
if (!confirm("Are you sure you want to submit empty fields?")) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
}
});
});
</script>
</head>
<body>
<form>
<input type="text" name="txt1" id="txt1" value="123" /><br />
<input type="text" name="txt2" id="txt2" value="" /><br />
<input type="text" name="txt3" id="txt3" value="abc" /><br />
<input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
</form>
</body>
</html>
Another way
$('input:text').filter(function() { return $(this).val() == ""; });
or
$('input:text').filter(function() { return this.value == ""; });
or
// WARNING: if input element does not have the "value" attribute or this attribute was removed from DOM then such selector WILL NOT WORK!
// For example input with type="file" and file does not selected.
// It's prefer to use "filter()" method.
// Thanks to #AaronLS
$('input:text[value=""]');
Working Demo
code from the demo
jQuery
$(function() {
$('#button').click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
var string = "The blank textbox ids are - \n";
emptyTextBoxes.each(function() {
string += "\n" + this.id;
});
alert(string);
});
});
You could also do it by defining your own selector:
$.extend($.expr[':'],{
textboxEmpty: function(el){
return $(el).val() === "";
}
});
And then access them like this:
alert($(':text:textboxEmpty').length); //alerts the number of text boxes in your selection
$(":text[value='']").doStuff();
?
By the way, your call of:
$('input[id=cmdSubmit]')...
can be greatly simplified and speeded up with:
$('#cmdSubmit')...
As mentioned in the top ranked post, the following works with the Sizzle engine.
$('input:text[value=""]');
In the comments, it was noted that removing the :text portion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :text is added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.
So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.
$("input[type=text][value=]")
After trying a lots of version I found this the most logical.
Note that text is case-sensitive.
There are a lot of answers here suggesting something like [value=""] but I don't think that actually works . . . or at least, the usage is not consistent. I'm trying to do something similar, selecting all inputs with ids beginning with a certain string that also have no entered value. I tried this:
$("input[id^='something'][value='']")
but it doesn't work. Nor does reversing them. See this fiddle. The only ways I found to correctly select all inputs with ids beginning with a string and without an entered value were
$("input[id^='something']").not("[value!='']")
and
$("input[id^='something']:not([value!=''])")
but obviously, the double negatives make that really confusing. Probably, Russ Cam's first answer (with a filtering function) is the most clear method.
Building on #James Wiseman's answer, I am using this:
$.extend($.expr[':'],{
blank: function(el){
return $(el).val().match(/^\s*$/);
}
});
This will catch inputs which contain only whitespace in addition to those which are 'truly' empty.
Example: http://jsfiddle.net/e9btdbyn/
I'd recommend:
$('input:text:not([value])')
This will select empty text inputs with an id that starts with "txt":
$(':text[value=""][id^=txt]')
Since creating an JQuery object for every comparison is not efficient, just use:
$.expr[":"].blank = function(element) {
return element.value == "";
};
Then you can do:
$(":input:blank")
I am trying to prefill some fields which are passed from URL as parameter pair. Having
www.example.com.com/myForm#myinput=123
as href send to end users, I am going to prefill the form field "myinput" with "123" after opening the link. However, the users will also see www.example.com.com/myForm#myInput=123 in their browser.
That's why I want to erase "myInput=123" from their URL. The reason for doing that is I don't want my users to see or even change the values in URL while filling the form.
I've tried
history.pushState(null, '', '/modifedURL')
either in HTML body "onload" or jquery "doc ready". As far I tried so far, this works only standalone without any parameter in URL like "www.example.com.com/myForm", but not with the additional injected parameters.
Here is simplified version of code what I got so far. Notice that the modifyURL Method is called successfully, but takes no effect on URL:
<head>
<meta charset="utf-8" />
</head>
<body onload="prefill();">
Your Body Content
<!-- Scripts at the bottom for improved performance. -->
<!-- jQuery, required for all responsive plugins. -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form id="myForm" method="POST">
<input id="myinput" maxlength="50" name="myinput" type="text" />
<br>
<input type="submit" name="submit" />
</form>
<script>
$(document).ready(function() {
//do some code after html is loaded
});
/*
window.onload = function () {
}
*/
function prefill() {
try{
var currentURL = window.location.href;
var n = currentURL.search("#");
var sPageURL = currentURL.substring(n+1);
var urlVal = getURLVal(sPageURL);
document.forms["myForm"]["myInput"].value = urlVal;
//change URL is called, but cannot change the URL!
modifyURL();
} catch(e){
alert("error " + e);
return false;
}
return true;
}
function modifyURL() {
history.pushState(null, '', '/modifedURL');
//even alert will fire, so pushState is skipped!!
alert('URL modified');
}
function getURLVal(query) {
//parse parameter pair in url
}
</script>
</body>
You can include the data diretly in your HTML, if it's meant to always be the same.
There are two ways:
1. <input id="myinput" maxlength="50" name="myinput" type="text" value="123" />
this actually puts the value inside your input field
2. <input id="myinput" maxlength="50" name="myinput" type="text" placeholder="123" />
this only displays it before any real value is inserted by the user (on submit you don't get any value)
I hope this is useful for you
I'm working on getting data to go from one textbox to another using javascript. Im new to Javascript and im getting a document undefined or null error.
<!DOCTYPE html>
<html>
<head>
<script>
function doit() {
window.document.form1.txtbox1.value= window.document.form2.txtbox2.value;
}
</script>
</head>
<body>
<form name="form1">
Enter your name:
<input type="text" name="txtbox1" value="">
<input type="button" name="btn1" value="Click" onclick="doit()">
</form>
<br><br><br>
<form name="form2">
Results:
<input type="text" name="txtbox2" value="">
</form>
</body>
</html>
It seems that you are trying access the element as a property of the DOM.
Instead, you should use document.getElementsByName method.
Revised function:
function doit(){
// The [0] is for accessing the first item.
// If you are unfamiliar with arrays, visit
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
document.getElementsByName("txtbox1")[0].value = document.getElementsByName("txtbox2")[0].value;
}
You need to switch (swap) them :
window.document.form1.txtbox1.value= window.document.form2.txtbox2.value;
When you click a button - you set the value of the second input to the first one and probably the second input called 'Result' is empty.
Try:
function doit() {
window.document.form2.txtbox2.value = window.document.form1.txtbox1.value;
}
There should not be any error, it's just pass data in another direction as you probably expect.
Give a unique ID to both the input element.
<input type="text" id="txtbox1" value="">
<input type="text" id="txtbox2" value="">
and in function doit()
document.getElementById("txtbox2").value = document.getElementById("txtbox1").value
I have a form I cobbled together with bits of code copied online so my HTML and Javascript knowledge is VERY basic. The form has a button that will add another set of the same form fields when clicked. I added some code to make it so that if the "Quantity and Description" field is not filled out, the form won't submit but now it just keeps popping up the alert for when the field's not filled out even if it is. Here's is my script:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
And here's my HTML:
<form action="MAILTO:ayeh#janusetcie.com" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
How can I get it to submit but still check every occurence of the "Quantity and Description" field?
First, I would not use spaces in your input names, as then you have to deal with weird escaping issues. Use something like "QuantityAndDescription" instead.
Also, it looks like you're trying to have multiple fields with the same name. The best way to do that is to add brackets to the name, meaning the values will be grouped together as an array:
<textarea name="QuantityAndDescription[]"></textarea>
This also means the code has to get all the textareas, not just the first. We can use jQuery to grab the elements we want, to loop over them, and to check the values. Try this:
function checkform()
{
var success = true;
// Find the textareas inside id of "comform", store in jQuery object
var $textareas = $("form#comform textarea[name='QuantityAndDescription[]']");
// Loop through textareas and look for empty values
$textareas.each(function(n, element)
{
// Make a new jQuery object for the textarea we're looking at
var $textarea = $(element);
// Check value (an empty string will evaluate to false)
if( ! $textarea.val() )
{
success = false;
return false; // break out of the loop, one empty field is all we need
}
});
if(!success)
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
// Explicitly return true, to make sure the form still submits
return true;
}
Also, a sidenote of pure aesthetics: You no longer need to use the CDATA comment hack. That's a holdover from the old XHTML days to prevent strict XML parsers from breaking. Unless you're using an XHTML Strict Doctype (and you shouldn't), you definitely don't need it.