I'm making an application where the user fills out all the information for a logo and adds it to a list where he can then add more logos or delete them.
Imagine I add a logo to the list with the following information:
Name: Pepsi
Location: Front, Back
Dimensions: 90mm, 60mm
Colors: Red, Blue, White
Options: Whitebg
Comment: This is a cool logo.
The array would be:
logos[logo[name, loc[], dim[], col[], opt[], com]]
Now I can do this to retrieve some info:
logos[0][0] //Prints "Pepsi"
logos[0][1][0] //Prints "Front"
logos[0][2][1] //Prints "60mm"
Now comes the problem. Whenever the user completes all the info and adds the logo the list I want to empty all the arrays except the main "logos" one so the user can add another logo to the list.
I tried to empty the "logo" array at the end of the "add" button function:
logo.length = 0;
But now the main array "logos" contains one "logo" array witch is empty. I want to keep that information there.
I think you could look at this differently.
I think you should just have a main logos array. And a Logo Object.
The Logo Object.
function Logo(name,loc, dim, col, opt, com){
return {
name:name,
loc:loc,
dim:dim,
col:col,
opt:opt,
com:com
}
}
var logos = [];
logos.push(Logo("blah",somthing[],else[]....);
Then reference by:
logos[0].name;
logos[0].dimensions[0];
....
you can add another...
logos.push(Logo("another",....));
Another Option
Same thing as before.
But instead of a Logos[]
Use a Logos = {} object.
You can dynamically add properties by given input like this.
Logos["First"] = Logo(loc,dim,col,opt,com);
Logos["Second"] = Logo(loc2,dim2,col2,opt2,com2);
If the user inputs that they want the "First" logo.
You can use
var firstlogo = Logos["first"];
firstlogo.loc[0] etc.
Play around with it, using objects provides a better understanding of the data you are dealing with, esp when multidimensional arrays are not "required"
I think you want do this :
var tempLogo = new Array();
tempLogo[0] = logos[0]; // or the logo you have choose
// Clear the logo
logos.clear();
// Set the logos with the tempLogo value
logos = tempLogo;
Finally I used objects instead of arrays as "Bodman" suggested. Works much better and is simpler.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="utf-8" />
<link href="css/reset.css" rel="stylesheet" type="text/css"/>
<link href="css/master.css" rel="stylesheet" type="text/css" media="screen"/>
</head>
<body>
<form action="/" method="post" id="form">
<p><label for="">Name:</label><input type="text" id="name"/></p>
<p><label for="">Location:</label><input type="checkbox" name="loc" value="Front"/> Front <input type="checkbox" name="loc" value="Back"/> Back <input type="checkbox" name="loc" value="Right"/> Right <input type="checkbox" name="loc" value="Left"/> Left</p>
<p><label for="">Dimensions:</label>H: <input type="text" size="4" id="dimH"/> W: <input type="text" size="4" id="dimW"/></p>
<p><label for="">Colors:</label><input type="text" size="4" id="col1" /> <input type="text" size="4" id="col2" /> <input type="text" size="4" id="col3" /> <input type="text" size="4" id="col4" /></p>
<p><label for="">Comments:</label><textarea id="com" cols="30" rows="2"></textarea></p>
<p><label for=""> </label><input type="button" id="add" value="Add" /> <input type="button" id="del" value="Del" /></p>
</form>
<ul id="results"></ul>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
CSS:
body { padding: 50px; }
p { margin: 10px 0; }
label { float: left; width: 100px; }
input { margin: 0 }
ul input[type="checkbox"]{ float:left; }
ul { list-style: none;}
li { margin: 10px 0; }
li div { margin-left: 20px; }
h2 { font: bold 14px Arial; margin-bottom: 5px; }
jQuery:
$(function(){
function logo(name, loc){
var locSize = loc.length;
return {
name: name,
loc: loc,
locSize: locSize
}
}
var logos = [];
$("#add").click(function(){
var name = $("#name").val();
var loc = [];
$("input[name='loc']:checked").each(function(){
loc.push($(this).val());
});
logos.push(logo(name, loc));
$("#results").children().remove();
$.each(logos, function(n){
$("#results").append("<li><input type='checkbox'/><div><h2>" + logos[n].name + "<h2/> Locations(" + logos[n].locSize + "): " + logos[n].loc.join(", ") + "<div/></li>");
});
});
$("#del").click(function(){
$("#results input[type='checkbox']:checked").each(function(){
var index = $(this).closest("li").index();
logos.splice(index, 1);
$(this).closest("li").remove();
});
});
Related
I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>
Hi Im new to javascript
i'm trying to change an image based on what the user chooses from a select input.
i want to link what what the user chooses from the select and an array
id also love for it to be in javascript and not jquery
this is what ive managed so far but im stuck with why its telling me undefined
<html>
<body>
<style>
.cta {
padding: 10px 20px;
background-color: red;
color: #ffffff;
display: block;
width: 180px;
text-align: center;
}
</style>
<div>
<label for="fullname">First name:</label>
<input name="fullname" class="sig_fullName" type="text" placeholder="Full name">
<br>
<label>Job title</label>
<input class="sig_jobTitle" type="text" placeholder="Last name">
<br>
<label>phone number</label>
<input class="sig_mobile" type="text" placeholder="Mobile">
<br>
<label for="company">Company:</label>
<select name="company" class="sig_company">
<option value="">please select</option>
<option value="">company1</option>
<option value="">company2</option>
<option value="">company3</option>
</select>
</div>
<a class="cta" onclick="generate();">Generate</a>
<div>first name: <span class="name"></span></div>
<div>Job title: <span class="job"></span></div>
<div>Phone number: <span class="number"></span></div>
<img class="companylogo" src="./img/example.jpg">
<script>
function generate() {
var fullName = document.querySelector(".sig_fullName").value;
var jobTitle = document.querySelector(".sig_jobTitle").value;
var Mobile = document.querySelector(".sig_mobile").value;
document.querySelector(".name").innerHTML = fullName;
document.querySelector(".job").innerHTML = jobTitle;
document.querySelector(".number").innerHTML = Mobile;
var swap = [
'./img/company1.svg',
'./img/company2.svg',
'./img/company3.png',
]
var logo = document.querySelector(".companylogo");
var dropdown = document.querySelector(".sig_company");
logo.src = swap.value;
}
</script>
</body>
</html>
I think the issue is in the way your accessing a property within the swap array
Try
logo.src = swap[dropdown.selectedIndex - 1];
The dropdown will have a selectedIndex value, it's 0 based like arrays, but because the first value is "please select" we need to minus one from the selectedIndex to correctly align it with the array of images.
What I want to try to do is kind of tricky so I will list the steps and my code below.
When the page opens the user is presented two options via checkboxes. On load neither are defaulted as checked. If the user checks the top one and decides they dont want that one the other should be cleared.
Whatever ends up being selected and they press Submit, I would like that array to populate the screen. Right now its just dummy names but will change. If after loading the array and they want to change to the other check box, the array on the screen needs to be cleared and the other one loaded with breaks between them. That holds true for either one they choose.
Ive posted my code so far below. The html renders correctly. What I dont know how to do is load the arrays. Just learning JS but this was presented to me to get done.
<script>
var cash = ["Susan", "Billy", "Jennifer"];
document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
document.write(cust[0]);
</script>
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" id="Cash Applications" name="Cash Applications" value="Cash Apps">
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" id="Customer Service" name="Customer Service" value="Customer Service">
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
</body>
</html>
Checkboxes usually let the user select more than one. Your restriction of only allowing one to be selected is kind of nonstandard so I've changed them to radio buttons.
You've also got an action on your form, which will cause it to load another page. I added an onclick handler which stops it from submitting.
var cash = ["Susan", "Billy", "Jennifer"];
//document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
//document.write(cust[0]);
function do_submit() {
// Decide which list to use:
var list = null;
if ( document.getElementById('Cash Applications').checked ) {
list = cash;
}
if ( document.getElementById('Customer Service').checked ) {
list = cust;
}
if ( list == null ) {
alert( 'Please select a list.' );
} else {
Put the list items on the page in the 'list' div:
let listElement = document.getElementById( 'list' );
listElement.innerHTML = '';
list.forEach( function( name ) {
listElement.innerHTML += name + '<br>';
});
}
return false;
}
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php" onsubmit="return do_submit();">
<input type="radio" id="Cash Applications" name="name" value="Cash Apps">
<label for="CashApplications"> Cash Applications</label><br>
<br>
<input type="radio" id="Customer Service" name="name" value="Customer Service">
<label for="Customer Service"> Customer Service</label><br>
<br>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
<div id="list">names will appear here</div>
</body>
</html>
So, your current scripts just directly append with document.writes. You need to define some elements to hold the info you want to display/update. I defined a div named "displaySelected". It starts out empty.
To handle the toggle of checkboxes you need some onclick functions for each checkbox... I defined a single one named selectBox and passed in a string to tell the function which checkbox was checked. In that function if cash was clicked then I clear cust and if cust was checked then I clear cash.
To handle displaying the selection you need an onclick function for the submit button. I created one named selectArray(). It clears out the contents of the displaySelected div and then creates an unordered list element then loops through whichever array was selected and creates list item elements and populates their text with the item from the array. Use the appendChild() function to add the li to the ul and the ul to the div
To handle clearing the selection you need an onclick function for the clear button. I created one named clearSelection(). It unchecks both boxes and then clears out the contents of the displaySelected div by setting its innerHTML to ''
var cash = ["Susan", "Billy", "Jennifer"];
var cust = ["David", "Larry", "Melissa"];
var cashBox = document.getElementById("Cash Applications");
var custBox = document.getElementById("Customer Service");
var displayDiv = document.getElementById("displaySelected");
function selectBox(box) {
switch (box) {
case 'cash':
custBox.checked = false;
break;
case 'cust':
cashBox.checked = false;
break;
default:
break;
}
}
function selectArray() {
displayDiv.innerHTML = '';
var uList = document.createElement("ul");
if (cashBox.checked) {
for (var cashIndex = 0; cashIndex < cash.length; cashIndex++) {
var cashEle = document.createElement("li");
cashEle.innerText = cash[cashIndex];
uList.appendChild(cashEle);
}
} else if (custBox.checked) {
for (var custIndex = 0; custIndex < cust.length; custIndex++) {
var custEle = document.createElement("li");
custEle.innerText = cust[custIndex];
uList.appendChild(custEle);
}
}
displayDiv.appendChild(uList);
}
function clearSelection() {
cashBox.checked = false;
custBox.checked = false;
displayDiv.innerHTML = '';
}
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<center>
<img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" id="Cash Applications" name="Cash Applications" value="Cash Apps" onclick="selectBox('cash')">
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" id="Customer Service" name="Customer Service" value="Customer Service" onclick="selectBox('cust')">
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<br>
<input type="submit" value="Select" onclick="selectArray()">
<button type="Clear Selection" id="button1" onclick="clearSelection()">Clear</button>
</form>
<br><br>
<div id="displaySelected">
</div>
</center>
</body>
</html>
This is not as elaborate as the previous answer, but it still works.
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<script>
var cash = ["Susan", "Billy", "Jennifer"];
document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
document.write(cust[0]);
function doChkClick(e) {
//get references to elements
spn = document.getElementById('spnout');
chkcash = document.getElementById('chkCash');
chkcust = document.getElementById('chkCust');
// reverse other checkbox
if (e === chkcash && e.checked) chkcust.checked = false
if (e === chkcust && e.checked) chkcash.checked = false
// show array
if (chkcash.checked) spn.innerHTML = cash.join(' ')
if (chkcust.checked) spn.innerHTML = cust.join(' ')
// if nothing checked
if (!chkcash.checked && !chkcust.checked)
spn.innerHTML = '[Empty]'
}
</script>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" name="Cash Applications" value="Cash Apps" id="chkCash" onclick=doChkClick(this)>
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" name="Customer Service" value="Customer Service" id="chkCust" onclick=doChkClick(this)>
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<b><span id="spnout">[Empty]</span></b>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
</body>
</html>
If you prefer to have the script separate from the html, you can use these files:
main.js
var cash = ["Susan", "Billy", "Jennifer"];
document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
document.write(cust[0]);
function doChkClick(e) {
//get references to elements
spn = document.getElementById('spnout');
chkcash = document.getElementById('chkCash');
chkcust = document.getElementById('chkCust');
// reverse other checkbox
if (e === chkcash && e.checked) chkcust.checked = false
if (e === chkcust && e.checked) chkcash.checked = false
// show array
if (chkcash.checked) spn.innerHTML = cash.join(' ')
if (chkcust.checked) spn.innerHTML = cust.join(' ')
// if nothing checked
if (!chkcash.checked && !chkcust.checked)
spn.innerHTML = '[Empty]'
}
main.htm
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
<script src="main.js"></script>
</head>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" name="Cash Applications" value="Cash Apps" id="chkCash" onclick=doChkClick(this)>
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" name="Customer Service" value="Customer Service" id="chkCust" onclick=doChkClick(this)>
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<b><span id="spnout">[Empty]</span></b>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
</body>
</html>
I have a website that when the user leaves any of the text fields blank, the border of the box will turn red. I figured it out in css with these lines of code
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
But I want to implement this in my php code if the fields are empty. I've been searching this all around an cannot find a solution. I even tried JavaScript and got to this point
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($email)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($password)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(!empty($fullname) && !empty($email) && !empty($password)){
echo "you're in";
}
But it is not working. So all I want to do is when the user leaves a field empty, the border of the box will turn red and the outline will be none.
getElementsByClassName returns an array, so you cannot assign properties like style.
Here's the JavaScript you want:
var inputs= document.getElementsByClassName("input-box");
for(var i=0; i<inputs.length; i++) {
inputs[i].style.borderStyle = 'solid';
inputs[i].style.border = '';
inputs[i].style.borderColor = 'red';
}
My Code is based on jQuery.
Hope It will help you...
$('#user-form').submit(function(e) {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
var dob = $('#dob').val();
if(name=="") $('#name').addClass('input-box'); else $('#name').removeClass('input-box');
if(email=="") $('#email').addClass('input-box'); else $('#email').removeClass('input-box');
if(phone=="") $('#phone').addClass('input-box'); else $('#phone').removeClass('input-box');
if(address=="") $('#address').addClass('input-box');else $('#address').removeClass('input-box');
if(dob=="") $('#dob').addClass('input-box'); else $('#dob').removeClass('input-box');
if((name=="")||(email=="")||(phone=="")||(address=="")||(dob==""))event.preventDefault();
});
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="user-form" action="q.php">
<p><label>Name : </label><input type="text" id="name" name="name" /></p>
<p><label>Email : </label><input type="text" id="email" name="email" /></p>
<p><label>Phone : </label><input type="text" id="phone" name="phone" /></p>
<p><label>Address : </label><input type="text" id="address" name="address" /></p>
<p><label>DOB : </label><input type="text" id="dob" name="dob" /></p>
<p><button type="submit" id="submit">Submit</button></p>
</form>
While I am not a big fun of mixing PHP/server code with front end like that, there is an obvious error (unless it was intended). Since you are using class input-box for all, if any one field is empty, all will be marked as empty.
Anyway, try the following:
first, the styles you want to apply for empty fields are the same. So, in your css file define one. E.g.
.needed-field {border:1px solid red;}
Then give each field a unique id while keeping the class input-box in place.
Then do two things in your PHP file: remove any possible bad field from before when submitting the form or something:
$('.input-box').removeClass('needed-field');
Then for each one:
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
$('#fullname').addClass('needed-field');
</script>
";
}
Hope that helps.
Edit:
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<style>
.needed_field {border:5px solid red;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="so/1.php" method="post">
<input type="text" id="fullname" name="fullname" class="input-box"><br/>
<input type="text" id="email" name="email" class="input-box"><br/>
<input type="text" id="password" name="password" class="input-box"><br/>
<input type="submit" value="Sumbit" id="submit" name="submit">
</form>
<script>
$('.input-box').removeClass('needed_field');
<?php
if($_POST['submit']){
//echo '<script>'
//echo '</script>';
$fullname=$_POST['fullname'];
$email=$_POST['email'];
$pwd=$_POST['pwd'];
if(empty($fullname)){
echo "$('#fullname').addClass('needed_field');";
}
}
?>
</script>
</body>
</html>
So i have a program where it starts off with one input field, and if you press the plus button it adds new input field. I also have it so it gives the new input field a different id. I would prefer it so when i press calculate, it saves the values of all the input fields data into an array. I have tried using a for loop with .val(), but that didnt work.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<!-- ************where the input fields are*******-->
<div id="append">
<p style="display:inline-block; margin-bottom:0px;">
<input type='text' class='minutes' id="minute1"/>
<input type='text' class='vidseconds' id="second1"/>
</p>
<div id="plusnminus">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
</div>
<!-- when this is pressed i want it to save the input fields data-->
<p id="calculate">Calculate</p>
</body>
</html>
//JavaScript
$(document).ready(function(){
var mins = [];
//where it add the new input field
var idnum = 1;
$("#plus").click(function(){
idnum+=1;
var input = "<p><input type='text' class='minutes' id='minute"+idnum+"' /><input type='text' class='vidseconds' id='second"+idnum+"'/></p>";
$(input).appendTo("#append");
});
// to remove an input field
$("#minus").click(function(){
if(idnum >= 2){
$("#minute" + idnum+ ", #second" + idnum).remove();
idnum-=1;
}
});
// i want it to put all of the data from the input fields in an array in that click function
$("#calculate").click(function(){
});
});
/*StyleSheet */
#append {
display: inline-block;
}
#plusnminus {
display: inline-block;
}
button {
border-style: none;
background-color: #C0C0C0;
width: 24px;
height: 24px;
}
Everything is inline because i'm trying to keep it a single file. I have placed comments however for readability.
You can use $.map(), selectors #append input[id^=minute], #append input[id^second] to get all input elements that are descendants of #append element; return an array containing two arrays of values, utilize destructuring assignment to set variable identifiers; for example, minutes, seconds, for arrays corresponding to .value of element where id begins with "minute" or "second"
$(document).ready(function() {
var mins = [];
//where it add the new input field
var idnum = 1;
$("#plus").click(function() {
idnum += 1;
var input = "<p><input type='text' class='minutes' id='minute"
+ idnum
+ "' /><input type='text' class='vidseconds' id='second"
+ idnum
+ "'/></p>";
$(input).appendTo("#append");
});
// to remove an input field
$("#minus").click(function() {
if (idnum >= 2) {
$("#minute" + idnum + ", #second" + idnum).remove();
idnum -= 1;
}
});
// i want it to put all of the data
// from the input fields in an array
// in that click function
$("#calculate").click(function() {
var [minutes, seconds] = $.map([$("#append input[id^=minute]")
, $("#append input[id^=second]")]
, function(el) {
return [$.map(el, function(elem) {
return elem.value;
})]
});
// do stuff with `minutes`, `seconds` variables
console.log("minutes:", minutes, "seconds:", seconds);
});
});
#append {
display: inline-block;
}
#plusnminus {
display: inline-block;
}
button {
border-style: none;
background-color: #C0C0C0;
width: 24px;
height: 24px;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<!-- ************where the input fields are*******-->
<div id="append">
<p style="display:inline-block; margin-bottom:0px;">
<input type='text' class='minutes' id="minute1" />
<input type='text' class='vidseconds' id="second1" />
</p>
<div id="plusnminus">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
</div>
<!-- when this is pressed i want it to save the input fields data-->
<p id="calculate">Calculate</p>
</body>
</html>
You can alternatively substitute Array.from() for $.map()
var [minutes, seconds] = Array.from([$("#append input[id^=minute]")
, $("#append input[id^=second]")]
, function(el) {
return Array.from(el, function(elem) {
return elem.value;
});
});
If you wrap your input fields in a form, you can use .serialize() or .serializeArray() to serialize the whole form at once.
$(function() {
$('#my-button').on('click', function() {
var values = $('#my-form').serializeArray();
console.log(values);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="input1" value="first field"><br/>
<input type="text" name="input2" value="second field"><br/>
<input type="text" name="input3" value="third field"><br/>
</form>
<button id="my-button">Get All Values</button>