Getting elements and values from inside parent div of button click - javascript

So I'm still new to JS and jQuery, but I'm trying to learn how to get all the elements and the values inside a div when I click a button inside it.
I was able to get it working for a form when I used FormData to do it. I can't figure out how to do it with a div instead of a form. (I would just use a form, but can't for this unfortunately.)
Here is what I got so far, but I know I'm doing something wrong.
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div");
console.log(myArea);
var myAreaData = new FormData(myArea[0]);
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>

You can use serializeArray for each input.
var myArea = $(this).closest("div").find(':input');
var myAreaData = myArea.serializeArray();
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div").find(':input');
//console.log(myArea);
var myAreaData = myArea.serializeArray();
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>

Related

Why my secont event listerner won't work after the first one

I have a profile page and there is an edit button. When I click the edit button you can edit the information on the page.
The thing is the second event listener won't work when I click the button done which is appeared after clicking the edit button, nothing changes.
```const editButton = document.querySelector('.edit-btn');
const doneButton = document.querySelector(".done-btn");
const textBox = document.querySelector('.txt-box');
const textArea = document.querySelector('.description');
const pwbox = document.querySelector('.pw-box');
const dateBox = document.querySelector(".date-joined");```
editButton.addEventListener('click', e => {
textBox.removeAttribute('readonly');
textArea.removeAttribute('readonly');
textBox.style.borderBottom = '1px gray solid';
pwbox.style.display = "flex";
doneButton.style.display = "block";
editButton.style.display = 'none';
dateBox.style.display = "none";
});
doneButton.addEventListener('click', e => {
textBox.setAttribute("readonly");
textBox.style.removeProperty('background color');
textBox.style.removeProperty('border-bottom');
pwbox.style.display = "none";
doneButton.style.display = "none";
editButton.style.display = 'block';
dateBox.style.display = "flex";
});
<div class="infobox">
<input type="text" name="uname" class="uname txt-box" value="<?php echo $usersName ?>" readonly autocomplete="off">
<input type="text" name="email" class='email' value="<?php echo $usersEmail ?>" readonly>
<div class="pw-box">
<label for="password">Password</label>
<input type="password" name="password" class="password">
<label for="confirmPassword">Confirm Password</label>
<input type="password" name="conf-password" class="conf-password">
</div>
<div class=" date-joined">
<small>Date Joined</small>
<div>01/01/01</div>
</div>
</div>
<div class="description-box">
<textarea name="description" class="description" cols="30" rows="10" placeholder="Let me describe you!" readonly></textarea>
<button class='edit-btn'>Edit</button>
<button class="done-btn">Done</button>
</div>
The problem is the .setAttribute in my js file, it need 2 parameters instead of one. Thanks for helping out.
You should set the readonly attribute to true
textBox.setAttribute("readonly", true);
Instead of using an event listener, you could probably use this and call a function when you click the button <input type="button" class="button" onclick="editFunction()" value="Edit" />

How to create a 'add more' feature in HTML forms [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am creating a HTML form in which I need to create a 'add more' button so another field appears. Any help would be appreciated
This isn't possible in pure HTML, but it can easily be achieved using javascript!
Basic example
In the basic example, you have one input field. When you click the add field button an extra input gets added after the last inserted input.
$(document).on('click', '.add_field', function() {
$('<input type="text" class="input" name="field[]" value="">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Copy value
This example is almost the same as the example above with one difference. It copies the value of the previous input. This is done with help of the JQuery .val() method
$(document).on('click', '.add_field', function() {
let value = $('.input:last').val(); // gets the value of the previous input
$('<input type="text" class="input" name="field[]" value="' + value + '">').insertAfter('.input:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="input" name="field[]" value="">
</form>
<button type="button" class="add_field">Add field</button>
Input groups
You could also copy an entire input group with multiple input fields.
$(document).on('click', '.add_field', function() {
$('<div class="input-group"><input type="email" class="input" name="email[]" value="" placeholder="Your email"><input type="password" class="input" name="password[]" value="" placeholder="Your password"></div>').insertAfter('.input-group:last');
})
form {
padding: 20px;
}
input {
width: 100%;
margin-bottom: 5px;
}
.input-group {
border-bottom: 1px solid gray;
padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-group">
<input type="email" class="input" name="email[]" value="" placeholder="Your email">
<input type="password" class="input" name="password[]" value="" placeholder="Your password">
</div>
</form>
<button type="button" class="add_field">Add field</button>
If you need any more examples please leave a comment!
Please try instead,
$(".Addmore").click(function(e) {
e.preventDefault();
// make a separation line
$("#FormItems").append('<hr width="300px">');
// append the input field as your needs
$("#FormItems").append('<input name="user" type="text" placeholder="Username"><br>');
$("#FormItems").append('<input name="email" type="email" placeholder="Email Address">');
});
.formwrapper{
text-align:center;
}
input{
padding:3px;
margin-bottom:5px;
display:inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formwrapper">
<form>
<div id="FormItems">
<input name="user" type="text" placeholder="Username"><br>
<input name="email" type="email" placeholder="Email Address">
</div>
<input type="button" value="Add More" class="Addmore">
<input type="submit" value="Submit">
</form>
</div>
In a few lines of js and html you can get that :
<button class="add-input">Add one more input</button>
<form action="." method="GET">
<div class="inputs">
<input type="text" name="text[]">
</div>
<input type="submit" value="submit">
</form>
<script>
const addButton = document.querySelector('button.add-input')
const inputDiv = document.querySelector('form .inputs')
addButton.addEventListener('click', ()=>{ // button to add the inputs
let newInput = document.createElement('input')
newInput.name = 'text[]' // add the name of the input
newInput.type = 'text' // add the type of the input
// you can add other attributes before appeding the node into the html
inputDiv.appendChild(newInput)
})
</script>
and you will have this as a result (I used php to prompt the result)
you can add as many input you want/need.
Next step is just doing some css
I hope this is, what you mean
<form>
<input type="text">
<input type="submit" value="cta">
</form>
<button>Add More</button>
<script>
document.querySelector('button').addEventListener('click', () => {
let field = document.createElement('input');
// change field however you'd like
document.querySelector('form').insertBefore(field, document.querySelector('form:last-child'));
})
</script>
You cannot create this using HTML only, you will need javascript. You could use a frontend framework like react.js to make life easy.
For example in react, you could bind an onclick listener on the button and maintain an array of values as state. Use this array to map value to your input. Whenever user clicks the button, you can then simply push a defaultValue to the array and react will handle the rest.
Import React, { useState } from 'react';
const Page = ()=>{
const [ arr, setArr ] = useState([""]);
const handleAdd = ()=>{
setArr([...arr, ""]);
};
return <form>
{arr.map((elem, index)=><input
onChange={ //"implement logic to update value stored in array" }
value={elem}
key={index} /> )}
<button onClick={()=>handleAdd()}>Add</button>
</form>
}
Using Bootstrap and jquery
Only in html is not possible, you need some on click event to trigger the functionality that may change the html dom.
You can use vanilla javascript as well, here is example using jquery library.
It will dynamically add and remove the element
index.html
<!DOCTYPE html>
<html>
<head>
<title>YDNJSY</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<!-- <h1>Lets learn javascript</h1> -->
<div class="col-xs-12">
<div class="col-md-12">
<h3> Actions</h3>
<div id="field">
<div id="field0">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_id">Action Id</label>
<div class="col-md-5">
<input id="action_id" name="action_id" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="action_name">Action Name</label>
<div class="col-md-5">
<input id="action_name" name="action_name" type="text" placeholder=""
class="form-control input-md">
</div>
</div>
<br><br>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="col-md-4">
<button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
</div>
</div>
<br><br>
</div>
</div>
</body>
<script src="./index.js"></script>
</html>
index.js
$(document).ready(function () {
var next = 0;
$("#add-more").click(function (e) {
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = ' <div id="field' + next + '" name="field' + next + '"><!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_id">Action Id</label> <div class="col-md-5"> <input id="action_id" name="action_id" type="text" placeholder="" class="form-control input-md"> </div></div><br><br> <!-- Text input--><div class="form-group"> <label class="col-md-4 control-label" for="action_name">Action Name</label> <div class="col-md-5"> <input id="action_name" name="action_name" type="text" placeholder="" class="form-control input-md"> </div></div><br><br></div>';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >Remove</button></div></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source', $(addto).attr('data-source'));
$("#count").val(next);
$('.remove-me').click(function (e) {
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length - 1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});

Launching a new window and filling form values using Javascript

I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}

How to preserve entered input value and display it with label with updated value

I am trying to display entered input value with label every time when user click on the test button, the input value should be updated every time when user enter new value in input section that means previous value should be deleted.
here what i have tried but somehow i am not able to display entered value.
$(document).ready(function () {
var testBtnSrc = document.getElementById("test_btn_src");
testBtnSrc.addEventListener("click", function(){
$('inp_src_success').append($('inp_src').val());
});
});
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id = "inp_src_success">
<label>input value here </label>
</div>
<div>
<label>Enter</label>
<input id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Source Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required onkeypress="myFunction()" />
<div id = "inp_src1"></div>
<button id = "test_btn_src" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test</button>
</div>
try following jQuery code
$(document).ready(function () {
$('#test_btn_src').click(function(){
$('#inp_src_success').text($('#inp_src').val());
});
});
There was an issue with this line $('inp_src_success').append($('inp_src').val()); due to missing '#' for the ids.
Secondly, change the code to $('#inp_src_success label').html($('#inp_src').val()); so that you don't remove the label when you are updating with the new value
$(document).ready(function () {
var testBtnSrc = document.getElementById("test_btn_src");
testBtnSrc.addEventListener("click", function(){
$('#inp_src_success label').html($('#inp_src').val());
});
});
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id = "inp_src_success">
<label>input value here </label>
</div>
<div>
<label>Enter</label>
<input id = "inp_src" name="txtbox_ip_src" minlength="7" maxlength="15" class="form-control" type="text"
placeholder="Source Server Ip:"
pattern="(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
required />
<div id = "inp_src1"></div>
<button id = "test_btn_src" class="btn btn-primary success" type="button" style=" font-size: 10px; margin-top:7px;">Test</button>
</div>

Setting Checkbox Value in a serialized array in javascript

I am trying to get the value of a checkbox to store in my database, but my code crashes right after running the serialized array.
Here is the javascript:
$(function () {
$('.form-signin').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray(),
pname = data[0].value,
score = data[1].value,
cheatm = data[2].value;
var GameScore = Parse.Object.extend("GameScore");
var gs = new GameScore();
gs.set("score", parseInt(score));
gs.set("playerName", pname);
gs.set("cheatMode", cheatm === 'true');
gs.set("user", Parse.User.current());
.
.
.
It crashes after cheatm = data[2].value;
Here is the HTML:
<form class="form-signin" role="form">
<h2 class="form-signin-heading" id="login-greeting">Enter Game Score</h2>
<input type="text" name="Player Name" class="form-control" placeholder="Player Name" required="" autofocus="">
<input type="number" name="Score" class="form-control" placeholder="Score" required="">
<input type="checkbox" value = 'true'> Cheat Mode<br>
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</form>
You could give the check-box an id and call it in JavaScript like:
HTML:
<input type="checkbox" id="myCheckbox"/>
jQuery:
var isMyCheckboxChecked = $("#myCheckbox").is(":checked");

Categories