I would like to pick a random name out of a form that i can fill with names. I have a function to add more form field dynamicly.
Here is my code so far :
<form>
<div id="dynamicInput">
<input class="inputs" type="text" name="input1" placeholder='Type name' required>
<input class="inputs" type="text" name="input2" placeholder='Type name' required>
<input class="inputs" type="text" name="input3" placeholder='Type name' required>
<input class="inputs" type="text" name="input4" placeholder='Type name' required>
</div>
<input type="button" class="login login-submit" value="Add a member" onClick="addInput('dynamicInput');">
<input type="button" name="login" class="login login-submit" value="Roll the wheel!" onClick="rollIt();">
</form>
My Javascript functions are as follows :
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input class='inputs' type='text' name='input" + counter + "' placeholder='Type name' >";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function rollIt() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i]);
}
}
I have two questions :
My friends are laughin at my face because of the onClick usage. Is it that bad ?
How could i store the form values in a list ? I tried to show them with the rollIt function with no success.
maybe something like this:
function randomName(){
var inputs = document.getElementsByTagName('input');
randomName = document.querySelector('[name="input'+(Math.floor(Math.random() * inputs.length) + 1)+'" ]').value;
return randomname;
}
this simply returns random value of input[name="input+x"]
ps: document.querySelector is not supported by all platforms so to be sure just add a getElementByAttribute function you can get everywhere around the web
About your question : My friends are laughin at my face because of the onClick usage. Is it that bad ?
In fact, don't put inline javascript is better for some reasons :
Separate presentation from controller layer. (HTML / JavaScript).
So maintainability is improved because of the first reason for you and mates.
Better way to debug your code. You don't have to check multiples files, only .js
According to this post, you can't put inline js in cache and so improve your user experience.
So try to avoid those inline onclick usages.
Related
This is my question:
I got an jsp page, this jsp has many text fields like this:
<html:text property="cicPF" maxlength="9" style="text-transform: uppercase;" onfocus="disableIfeFields()"/>
So I want to disable some of this text fields when the focus it's in a specific field
But no one of this fields has "id" label, and I can't modify it to include it.
May I disable the fields usig their given names, no one of this repeats the same name.
for example with a function like this:
function disableIfeFields(){
document.getElementsByName("numIdentificacionPF").disabled = true;
}
thanks
You need to loop through the list and disable all the fields you want that way, used input to show example:
function disableIfeFields() {
document.getElementsByName("numIdentificacionPF").forEach((e) => {
e.disabled = true;
});
}
<html:text property="cicPF" maxlength="9" style="text-transform: uppercase;" />
<input onfocus="disableIfeFields()" type="text" name="fname">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
Maybe like this:
function disableIfeFields(){
document.querySelectorAll('[property="cicPF"]')[0].disabled = true;
}
disableIfeFields();
<input type="text" property="cicPF" maxlength="9" style="text-transform: uppercase;" onfocus="disableIfeFields()"/>
Hopefully the following should help. Because the selection result is a list of elements you will have to loop through the results.
Please note that since you said no input repeats the same name, I'm using querySelectorAll, which might be a more suitable method after all…
var inputs = document.querySelectorAll('input[type="text"]');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].id === 'label') {
continue;
}
inputs[i].disabled = true;
}
Given the following HTML:
<div id= "playerNames" class="playerInfo">
<form name="form1" method="post" action="http://examples.funwebdev.com/process.php" id="newGame">
<p id= "userInput">
<label>Player 1 name: </label></br><input type="text" name="p1" id="nameOne" value="" required></input></br>
<label>Player 2 name: </label></br><input type="text" name="p2" id="nameTwo" required></input> <input id="submit" type="submit" value="New Game"/>
</p>
</form>
</div>
And the following javascript:
$(document).ready(function () {
console.log("jQuery is ready to use...");
$("#newGame").on("submit", newGameListener);
});
function setUpUsers(){
var player_One = document.getElementById("nameOne").value;
var player_Two = document.getElementById("nameTwo").value;
document.getElementById("pTurns").innerHTML = (+nameTwo+ ", its your turn");
document.getElementById("pScores").innerHTML = (+nameOne+ ": 50pts </br>" (+nameTwo+ ": 50pts </br>"
}
function newGameListener(e) {
e.preventDefault();
setUpUsers();
}
I am trying to append these two variables (nameOne, nameTwo) within p elements. However when this code is run I get NaN (Not a Number) Instead of the user input as a string. Not sure how I should go about achieving this!
That's because you are converting a DOM element to a number. The result will be, em.., NaN. What you want is the value of the element. You can get the value by reading the .value property.
document.getElementById("pTurns").innerHTML = (+nameTwo.value + ", its your turn");
However, since you want to concatenate the value with a string there is no need to use + operator.
Also note that should not rely on the global variables (some browsers like Chrome creates global variables that refer to elements that have the corresponding IDs) for accessing the elements, it's fragile and may fail miserably. Yes, it has been standardized by HTML5, but in my opinion it's a bad practice. Use the document.getElementById method for selecting the elements by their id.
As #Vohuman and #guest271314 answered about your problem(NaN) but you have several syntax error in your HTML and javascript, however I fixed that I optimized your javascript.
Jsfiddle
$(document).ready(function() {
console.log("jQuery is ready to use...");
$("#newGame").submit(function(e) {
e.preventDefault();
var player_One = $('#nameOne').val();
var player_Two = $('#nameTwo').val();
$('#pTurns').html(player_One + ", its your turn");
$('#pScores').html(player_One + ": 50pts </br>" + player_Two + ": 50pts </br>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="playerNames" class="playerInfo">
<form name="form1" method="post" id="newGame">
<p id="userInput">
<label>Player 1 name:</label>
<br />
<input type="text" name="p1" id="nameOne" value="" required />
<br />
<label>Player 2 name:</label>
<br />
<input type="text" name="p2" id="nameTwo" required />
<input id="submit" type="submit" value="New Game" />
</p>
</form>
</div>
<p id="pTurns"></p>
<p id="pScores"></p>
newbie here, im trying to figure out why i get "Cannot read property 'elements' of undefined ".
javascript:
function conf()
{
for (i=0; i<5; i++)
{
box = document.project.elements[i];
if (!box.value)
{
alert('You haven\'t filled in ' + box.name + '!');
return false
}
}
return true;
}
html:
<form id="project" onsubmit="return conf()" action="#">
<fieldset>
<legend>Contact Details</legend>
<label for="txtname">Your Name:</label> <input type="text" class="text" name="txtname" id="1" /><br/>
<label for="txtemail">Email:</label> <input type="text" class="text" name="txtemail" id="2"/><br/>
<label for="txtartist">Artist:</label> <input type="text" class="text" name="txtartist" id="3"/><br/>
<label for="txtalbum">Song / Album:</label> <input type="text" class="text" name="txtalbum" id="4"/><br/>
<label for="txtcomments">Comments:</label> <textarea class="ta" name="txtcomments" id="txtcomments" cols="30" rows="20"></textarea><br/>
<input type="submit" class="buttons" id="btnSubmit" name="btnsubmit" value="Send Enquiry"/>
</fieldset>
</form>
To get at the form elements you need to use the form id,
document.getElementById('project').elements[i];
a better approach would be use the document.querySelectorAll() and get the elements you are interested in, which would be in this case,
document.querySelectorAll('#project input[type="text"], textarea')
which gives you an array of elements that you could loop through and perform the checks.
BTW, you will probably sooner or later start needing individual checks for each of the inputs. One approach to this would be use the new HTML5 input types.
The approach you have tried should work, since forms with an ID are made named properties of the document object. Perhaps you have another element with a name or id of project.
If the form is the only element with a name or ID of project, you write, formally:
document.forms.project.elements...
or shorter:
document.project.elements...
But that issue can be avoided. Since you have a submit listener on the form, you can pass a reference to the form directly by passing this:
<form id="project" onsubmit="return conf(this)" action="#">
And within the function (don't forget to declare variables!!):
function conf(form)
{
var box;
for (var i=0; i<5; i++) {
box = form.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
return false
}
}
return true;
}
Now you can change the form ID to anything (or remove it) and the function still works.
Also, the label element is associated with a form control by ID, not by name so:
<label for="txtalbum">Song / Album:</label> <input ... name="txtalbum" id="4">
should be:
<label for="4">Song / Album:</label> <input ... name="txtalbum" id="4">
Otherwise the label will not be associated with the element (and therefore may as well be a span or similar and not have a for attribute).
Lastly, please don't use XML syntax in an HTML document. In an HTML document, the / in <br /> and <input ... /> is simply ignored.
I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:
<input name="userfile[]" type="file" /><br />
<input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
Is added to a designated area? Keeping in mind adding a number onto the name if the button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question
If possible, I recommend adding jQuery to your project. It makes DOM manipulation easy.
http://api.jquery.com/category/manipulation/
An example might look like this
Add Item
<div id="#wrapper">
<input type="text" value="Description goes here." name="imagedescription1" maxlength="20" onfocus="this.value = '';" /><br />
<input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</div>
<script>
$(function(){
var i = 3; // i would be incremented with each add.
$("#myButton").click(function(){
$('<input type="text" value="Description goes here." name="imagedescription' + i + '" maxlength="20" onfocus="this.value = '';" /><br />').appendTo('#wrapper');
});
return false;
});
</script>
You can write a JS function for adding textboxes and call the function when the button is pressed.
The function should go along these lines....
var count;
function functionName()
{
count++;
document.Write('<input type="text" value="..." name="imagedescriptor'+count+'" max..');
}
Hopefully it works.
Try this:
var i = 2;
var sourceTextNode = document.getElementsByName("imagedescription2")[0];
function createTextBox(){
var newNode = sourceTextNode.cloneNode(false);
newNode.setAttribute("name", ++i);
var parent = sourceTextNode.parentNode;
if(parent.lastchild == sourceTextNode) {
parent.appendChild(newNode);
} else {
parent.insertBefore(newNode, sourceTextNode.nextSibling);
}
}
function btnClicked(){
createTextBox();
}
another jQuery solution:
Live Demo
$("#f_add").click(function(e) {
var field = document.createElement('input');
$(field).attr('type', 'text');
$(field).attr('name', 'field[]');
$("#thenewhotness").append(field);
e.preventDefault();
});
<form id="thenewhotness">
<button id="f_add">Add Extra Field</button>
<input type="text" name="field[]">
</form>