To get the nearest submit button using javascript - javascript

Following is a test code of what i want to achieve. I want to find the value of submit button when cancel is clicked. here i have use for loop. is there any other way without iterating.
<!DOCTYPE html>
<html>
<body>
<ol>
<input type="text" name="txt1">
<input type="text" name="txt2">
<input type="text" name="txt3">
<li><input type="button" value="cancel" name="cancel" onclick="myFunction()"></li>
<li><input type="button" value="undo" name="undo"></li>
<li><input type="submit" value="send mail" name="submit"></li>
</ol>
<script>
function myFunction() {
var elementsLI = document.getElementsByTagName('li');
var length = document.getElementsByTagName('li').length;
for(var i = 0; i <= length ; ++i){
if(elementsLI[i].childNodes[0].type == "submit"){
alert(elementsLI[i].childNodes[0].value);
}
//var y = elementsLI.childNodes[i].type == "submit";
}
}
</script>
</body>
</html>

You can get it using querySelector() method with attribute equals selector.
var submit = document.querySelector('li [type="submit"]');

Related

Fetching data from many input fields using getElementsByTagName() method

<!DOCTYPE html>
<html>
<head>
<script>
function getElements()
{
var v = document.getElementById('view');
var x=document.getElementsByTagName("input");
for(var i=0; i<x.length; i++){
v.innerHTML = x[i].value+"<br>";
}
}
</script>
</head>
<body>
<input type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
<input type="button" onclick="getElements()" value="How many input elements?">
<p id='view'></p>
</body>
</html>
This is my code where I want to fetch the values of the fields and iterate them below in the "p" tag but it kept showing me the value of the last input which is the submit value.
The nature of the program was for me to fetch data from many inputs elements including file, upload field and submit them to the server script.
You need to change your html and javascript as following which will not give you button's value(which is not needed) :
HTML:
<input type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
<button onclick="getElements()" value="How many input elements?" >How many input elements?</button>
<p id='view'></p>
JS:
function getElements()
{
var v = document.getElementById('view');
v.innerHTML = "";
var x=document.getElementsByTagName("input");
for(var i=0; i<x.length; i++){
v.innerHTML += x[i].value+"<br>";
}
}
DEMO : http://jsfiddle.net/f7bLq0b4/
Make the below change in your code to make it work.
<!DOCTYPE html>
<html>
<head>
<script>
function getElements()
{
var v = document.getElementById('view');
var x=document.getElementsByTagName("input");
for(var i=0; i<x.length; i++){
v.innerHTML += x[i].value+"<br>";
}
}
</script>
</head>
<body>
<input type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
<button onclick="getElements()">How many input elements?</button>
<p id='view'></p>
</body>
</html>
To append a string you need to use +=.

How to solve validation using multiple buttons in a form

I have a form, with a number of textboxes which a user can fill in. At the bottom of the form I have two buttons. One for canceling and one for submitting. Like the example below
<form action='bla.php' method='post'>
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<input type='submit' name='submit'>
<input type='submit' name='cancel'>
</form>
And I have a js function that checks the fields for their data which I used to use for both buttons. I therefor refer to the js function in the form as below:
<form action='bla.php' method='post' name='form' onSubmit='return CheckFields()'>
The js function looks like this:
function CheckFields() {
var formname = "form";
var x = document.forms[formname]["someTextField1"].value;
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
Now I want this js function to only run when using the submit and not the cancel button. When I try to move the call to the function to the submit button as below it doesn't work:
<input type='submit' name='submit' onClick='return CheckFields()'>
<input type='submit' name='cancel'>
Why? What is the smartest way of solving this? Should I leave the call to CheckFields() in the form and check within the script what button was clicked or should I remake the function to somewhat work with a button instead? Anyone have an idea or an example?
replace <input type='submit' name='cancel'> by <input type='button' name='cancel'>.Your Version actually has two submit-buttons, both of which will submit the form.
Watch this sample http://jsfiddle.net/355vw560/
<form action='bla.php' method='post' name="form">
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<br/>
<input type='submit' name='submit' onclick="return window.CheckFields()">
<input type='submit' name='cancel' value="cancel" onclick="return false;">
anyway it's always better to use jquery or event listeners instead of managing events directly in the dom.
The function didnt worked because its scope was the element, if u specify window as context your function works.
First at all, it's not needed have submit button on a form if you want to use javascript to check all the fields before submitting.
I think the smartest way of doing it will be as follow:
Your form (without action, submit button, and method. Only identifing each component with id's):
<form id="formId">
<input type='text' id="text1">
<input type='text' id="text2">
<input type='text' id="text3">
<input type='button' id="accept">
<input type='button' id="cancel">
</form>
Your javascript (you have to have jQuery added):
jQuery("#formId").on("click", "#accept", function(){ //listen the accept button click
if(CheckFields()){ //here you check the fields and if they are correct
//then get all the input values and do the ajax call sending the data
var text1 = jQuery("#text1").val();
var text2 = jQuery("#text2").val();
var text3 = jQuery("#text3").val();
jQuery.ajax({
url: "bla.php",
method: "POST",
data: {
"someTextField1":text1, //In your example "someTextField1" is the name that the bla.php file is waiting for, so if you use the same here, it's not needed to change anything in your backend.
"someTextField2":text2,
"someTextField3":text3
},
success: function(){
//here you can do whatever you want when the call is success. For example, redirect to other page, clean the form, show an alert, etc.
}
});
}
});
jQuery("#formId").on("click", "#cancel", function(){ //here listen the click on the cancel button
//here you can clean the form, etc
});
function CheckFields() { //here I did a little change for validating, using jQuery.
var x = jQuery("#text1").val();
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
I hope it helps you!
I handle it with this way , Hope it will help.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form method="post" action="/">
<div class="container" style="background: #efefef; padding: 20px;">
<label>Encrypt and decrypt text with AES algorithm</label>
<textarea name="inputText" id = "inputText" rows="3" cols="100" placeholder="Type text to Encrypt..." maxlength="16" ></textarea>
<br>
<br>
<textarea name="inputKey" id = "inputKey" rows="1" cols="100" placeholder="Type key to Encrypt\Decrypt text with..." maxlength="16"></textarea>
<br>
<br>
<label>SBox :</label>
<div>
<div class="s-box-radios">
<ul class="sbox">
<li>
<label>SBox 1
<input id="sbox1" name="sboxOption" type="radio" value="option1" required/>
</label>
</li>
<li>
<label>SBox 2
<input id="sbox2" name="sboxOption" type="radio" value="option2" />
</label>
</li>
<li>
<label>SBox 3
<input id="sbox3" name="sboxOption" type="radio" value="option3" />
</label>
</li>
<li>
<label>SBox 4
<input id="sbox4" name="sboxOption" type="radio" value="option4" />
</label>
</li>
</ul>
</div>
<div class="s-box-display">
<textarea rows="5" cols="10"></textarea>
</div>
</div>
<div class="clear"></div>
<br>
<label>Result of Decryption in plain text</label>
<textarea name="inputCipher" rows="3" cols="100" placeholder="Encrypted Texts..." name="decrpyted"></textarea>
<br>
<input type="submit" value="Encrypt" name="Encrypt" id ="encrypt" onclick="valEncrypt()" />
<input type="submit" value="Decrypt" name="Decrypt" id ="decrypt" onclick="valDncrypt()" />
</div>
</form>
<script>
function valEncrypt()
{
var inputText = document.getElementById('inputText');
var inputkey = document.getElementById('inputKey');
if (inputText.value.length <16)
{
doAlert(inputText);
return false;
}
else
{
removeAlert(inputText);
}
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
else
{
removeAlert(inputkey);
}
}
function valDncrypt()
{
var inputkey = document.getElementById('inputKey');
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
alert('!Success');
}
function doAlert(element){
element.style.border = "1px solid #FF0000";
}
function removeAlert(element){
element.style.border = "1px solid #000000";
}
</script>
</body>
</html>

Creating text fields according to user's input in JavaScript Function

I want to create text fields according to user's input and show the text fields through JavaScript function but this code is not working!
<html>
<head>
<title>Create text Fields according to the users choice!</title>
<script type="script/JavaScript">
function createTextField(){
var userInput = parseInt(document.form2.txtInput.view);
for(var i=0; i<=userInput;i++)
{
document.write('<input type="text">');
}
}
</script>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
Please Replace this line:
var userInput = parseInt(document.form2.txtInput.view);
To
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
function createTextField(){
// alert(document.getElementById('txtInput').value);
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
for(var i=0; i<userInput;i++)
{
document.write('<input type="text">');
}
}
<html>
<head>
<title>Create text Fields according to the users choice!</title>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput" id="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
You shouldn't use document.write. The correct way to do it is to append the inputs to a div.
Demo on Fiddle
HTML:
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>Input:
<input type="text" name="txtInput" />
<input type="button" name="btnInput" value="Create" />
<div></div>
</form>
JavaScript:
var btn = document.getElementsByTagName("input")[1];
btn.onclick = function () {
var userInput = parseInt(document.getElementsByTagName("input")[0].value, 10);
for (var i = 0; i <= userInput - 1; i++) {
document.getElementsByTagName("div")[0].innerHTML += "<input type='text' />"
}
};
Jquery is better option to add dynamic input/div's easy to manipulate DOM.
Check the following code
<div class="box">
<label> Enter input value </label>
<input type="number" id="in_num"/>
<button type="button" id="submit"> submit </button>
<h3> Append input values</h3>
<div id="dynamicInput"></div>
</div>
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +'/>');
}
});
});
Demo URl: http://jsfiddle.net/sathyanaga/75vbgesm/3/
Change:
var userInput = parseInt(document.form2.txtInput.view);
To:
var userInput = parseInt(document.getElementById("txtInput").value);
And give the input textbox an id (I used "txtInput", but it can be anything).
I believe you also need to change the loop from, when I typed "2" it created 3 inputs instead of 2.

Gather all selected elements in a form and their hidden inputs for submission

Think polaroids on a table and you are asked to go through them and decide yes or no for each one. Yes being keep it, No being throw it out.
I need a element for each photo, to be displayed on a page, in some sort of tile fashion with two check boxes, (keep/discard). If a element has its child checkboxes checked yes, then some javascript somewhere gathers said boxes and puts the information into an array when the user clicks submit.
Each element will have hidden information about the photo being selected, like filename, location, and galleryID. If the javascript detects that the parent element div is selected, as signified by the checked yes box, also include that information in the array.
The end result of the array will be passed to a php file, which eventually print out the results in a csv file.
Can I be assisted in pointed into the right direction? Here is a my fiddle http://jsfiddle.net/9uZX7/3/
Here is my html:
<form onsubmit="">
<div class="imageTile" id="$filename-1">
<img src="http://tinyurl.com/krawyh9"/><br>
<input type="hidden" name="imageFilename" value="$filename-1">
<input type="hidden" name="imageGalleryID" value="$galleryID-1">
<label for="$filename-1">Keep</label>
<input type="checkbox" value="1" id="$filename-1">
</div>
<br>
</form>
<form onsubmit="">
<div class="imageTile" id="$filename-2">
<img src="http://tinyurl.com/krawyh9"/><br>
<input type="hidden" name="imageFilename" value="$filename-2">
<input type="hidden" name="imageGalleryID" value="$galleryID-2">
<label for="$filename-2">Keep</label>
<input type="checkbox" value="1" id="$filename-2">
</div>
<br>
</form>
<div id="submit_buttons">
<button type="reset">Reset</button>
<button class="submit" type="submit" onclick="return false">Submit</button>
</div>
Here is my Javascript:
$(".submit").click(function(event){
event.preventDefault();
var checkedBoxes = $(".imageTile input:checkbox:checked")
var resultSet = $(".imageTile input:hidden")
for (var i=0; i<checkedBoxes.length; i++) {
if (checkedBoxes[i].checked) {
$(resultSet).map(function(){
return $(this).val();
}).get();
}
}// <----
console.log(resultSet);
});
I've made some modifications in your markup and JavaScript source:
HTML :
<form onsubmit="">
<div class="imageTile">
<img src="http://tinyurl.com/krawyh9"/><br>
<input class="data" type="hidden" name="imageFilename" value="$filename-1">
<input class="data" type="hidden" name="imageGalleryID" value="$galleryID-1">
<label for="$filename-1">Keep</label>
<input class="checkbox" type="checkbox">
</div>
<div class="imageTile">
<img src="http://tinyurl.com/krawyh9"/><br>
<input class="data" type="hidden" name="imageFilename" value="$filename-2">
<input class="data" type="hidden" name="imageGalleryID" value="$galleryID-2">
<label for="$filename-2">Keep</label>
<input class="checkbox" type="checkbox">
</div>
<div id="submit_buttons">
<button type="reset">Reset</button>
<input class="submit" type="submit" onclick="return false" value="Submit">
</div>
</form>
JavaScript :
$(".submit").click(function(event){
event.preventDefault();
var imageTile = this.parentElement.parentElement.getElementsByClassName('imageTile') ;
var l = imageTile.length ;
var data = [] ;
for(var i = 0 ; i < l ; i++){
if(imageTile[i].getElementsByClassName('checkbox')[0].checked){
var dat = imageTile[i].getElementsByClassName('data') ;
console.log(dat) ;
var ll = dat.length ;
var datArr = [] ;
for(var j = 0 ; j < ll ; j++){
datArr.push([dat[j].attributes['name'].value, dat[j].attributes['value'].value]) ;
}
data.push(datArr) ;
}
}
// Now 'data' is the array
// dataString is a JSON representation of the array to send to the server
var dataString = JSON.stringify(data) ;
// Test
console.log(data) ;
console.log(dataString) ;
/*
Do something with your data here
*/
});
I haven't used jQuery more than the $(".submit").click(function(event){ that you used.
There's no limitation of how many hidden inputs you have if the has className set as "data".
I'm not sure of what you are looking for, but the following JSFiddle should help you on the selectors at least : http://jsfiddle.net/9uZX7/4/
$(".submit").click(function(event){
event.preventDefault();
var divs = $(".imageTile:has(input:checkbox:checked) input:hidden");
console.log(divs);
});
Do you need the hiddens to be grouped by div ?

How to delete a check box using javascript

I'm working on this HTML Page where i can add a check-box along with the label by clicking the add button, is there anyway that i can have a delete button as well so that when i select a check-box and press the delete button the check-box along with the text box is deleted??Please find my code below!!
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function Add()
{
var checkbox=document.createElement('input');
var inps=document.createElement('input');
var output=document.getElementById('output');
checkbox.type='checkbox';
inps.type='text';
inps.name='textboxname';
checkbox.name='checkname';
output.appendChild(checkbox);
output.appendChild(inps);
output.appendChild(document.createElement('br'));
}
</script>
</head>
<body>
<form action="http://localhost:9990" method="post">
<span id="output"></span>
<input type="button" value="Add" onclick="Add()">
<center>
<p>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</center>
</form>
</body>
</html>
Give all of the check boxes that could potentially be deleted the same class. Additionally label all of the text boxes that could be deleted with their own class. My check boxes will be labeled with chk and my text boxes will be labeled with txt. As in:
<input type="checkbox" class = 'chk' /> and
<input type="text" class = 'txt' />
The following solution should work as long as check boxes and text fields are 1 to 1.
the function you will add to your delete button will loop through all of the check boxes and see if they are deleted and then delete the checked ones.
Heres the JS:
function delBoxes(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
for(var i = 0; i<boxes.length; i++){
box = boxes[i];
txt = texts[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
That will delete all of the checked check boxes, all you have to do now is make a button and add that function as an onclick.
<input type="button" value="Delete checked boxes" onclick = "delBoxes();" />
Sample HTML
<div>
<input type='checkbox' value='asd' id='test' name='test' />
<input type='checkbox' value='asd' id='tester' name='test' />
<input type='button' value='remove' id='rmvBtn' />
</div>
In pure javascript, you can do this,
var rmvBtn = document.getElementById('rmvBtn');
rmvBtn.addEventListener('click', function(){
var rmvCheckBoxes = document.getElementsByName('test');
for(var i = 0; i < rmvCheckBoxes.length; i++)
{
if(rmvCheckBoxes[i].checked)
{
removeElm(rmvCheckBoxes[i]);
}
}
});
function removeElm(elm){
elm.parentElement.removeChild(elm);
}
JS Fiddle
HTML
<input type="checkbox" id="checkboxid" name="checkboxname">
<button id="btnDeleteid" onclick="deleteCheckBox()" name="btnDeletename">Delete</button>
JavaScript
function deleteCheckBox(){
if (document.getElementById('checkboxid').checked){
var answer = confirm('Are you sure you want to delete this checkbox?');
if (answer)
{
$("#checkboxid").remove();
}
}else{
alert("Pls check the checkbox.");
}
}
I hope this will help.
Refer fiddle - http://jsfiddle.net/F8w8B/3/

Categories