how to get value of these inputs using javascript or jquery - javascript

I was wondering if it possible to find an input by it's closest element?
real code:
<form method="post" action="">
<div class="rocket-form">
<fieldset>
<legend>Person Contacts</legend>
</fieldset>
<div class="rocket-label-element no-height">
<dt id="id-label"> </dt>
<dd id="id-element">
<input type="hidden" name="id" value="" readonly="readonly" id="id">
</dd>
</div>
<div class="rocket-label-element no-height"><dt id="vendor_id-label"> </dt>
<dd id="vendor_id-element">
<input type="hidden" name="vendor_id" value="" readonly="readonly" id="vendor_id">
</dd>
</div>
<div class="rocket-label-element">
<div id="firstname-label">
<label for="firstname" class="rocket-label optional">First name</label>
</div>
<div class="rocket-element">
<input type="text" name="firstname" id="firstname" value="any first name" maxlength="64" readonly="readonly">
</div>
</div>
<div class="rocket-label-element">
<div id="lastname-label">
<label for="lastname" class="rocket-label optional">Last name</label>
</div>
<div class="rocket-element">
<input type="text" name="lastname" id="lastname" value="any last name" maxlength="64" readonly="readonly">
</div>
</div>
<div class="rocket-label-element">
<div id="phone-label">
<label for="phone" class="rocket-label optional">Phone</label>
</div>
<div class="rocket-element">
<input type="text" name="phone" id="phone" value="0123456789" maxlength="32" readonly="readonly">
</div>
</div>
<div class="rocket-label-element">
<div id="email-label">
<label for="email" class="rocket-label optional">Email</label>
</div>
<div class="rocket-element">
<input type="text" name="email" id="email" value="name#someMail.com" maxlength="128" readonly="readonly">
</div>
</div>
</div>
</form>
I have this form, and I want to get the value of the inputs in variables..
I tried to use "vendor_id" in order to use closest() or next() or prev() but no luck..
so, any help?

You can use
var vendorId = $("#vendor_id").val();
to get the value of vendor_id.
Be sure to include the # which identifies it as an id.
If you want to get the values of all the inputs, you can use:
$("input, select, textarea").each(function(){
// Get value of inputs
});
If you have more than one form, you may use:
var formData = $(".rocket-form").closest("form").serialize();
Remember you will need to include jQuery with a script tag and you should wrap your code like so:
$(function() {
console.log( "ready!" );
});
This ensures the page is ready before your JavaScript executes.

you can try this
var form = $("#vendor_id").closest("form").get();
$("form :input").each(function(){
var input = $(this);
var AllInputValues= $(input).val();
alert (AllInputValues);
});
EDIT
var theVendform = $("#vendor_id").parent().closest("form").get();
alert(theVendform["0"][3].defaultValue);
alert(theVendform["0"][4].defaultValue);
alert(theVendform["0"][5].defaultValue);
alert(theVendform["0"][6].defaultValue);

Not sure if I completely understand what you are asking but what about
$('#vendor_id-element input').val()

You a class in all your inputs where you want to get value, and do de following js
Array.prototype.slice.apply(document.querySelector('.your-input-class')).forEach(function(el){
Console.log(el.value);
});

try this
var inputs = $('form').find('input');
//inputs is the array of your inputs and values can be accessed by:
var value1 = $(inputs[0]).val();
//or you can use for loop or forEach
for (var i = 0; i < inputs.length; i++) {
var currentValue = $(inputs[i]).val();
alert(currentValue);
}

Related

Array.prototype.filter() returns empty list

I'm trying to filter a list of jQuery elements collected using the .siblings() method.
I have the html code:
<div>
<div>
<label for="username">Username</label>
<input class="form-control username" type="text" placeholder="Username" id="username"/>
</div>
<div>
<label for="Password">Password</label>
<input class="form-control password" type="password" placeholder="Password" id="password"/>
</div>
<div style="text-align:center;">
<button id="login">Login</button>
</div>
</div>
When the button is pressed, I collect the sibling divs using:
var elem = jQuery(this).parent('div').siblings('div:has(input)');
This returns an array of length 2 (containing the divs of both the username and password).
When I then check to see if the first item in this array has a child input tag with class 'username' the following code returns true.
jQuery(elem[0]).children('input').hasClass('username');
However, when I filter the array on this condition, an array of length 0 is returned. Why does this happen? Surely the array should contain 1 element since the condition evaluates to true on the first element?
var filteredElem = elem.filter(div => jQuery(div).children('input').hasClass('username'));
$('#login').click(function() {
var elem = jQuery(this).parent('div').siblings('div:has(input)');
var filteredElem = elem.filter(div => jQuery(div).children('input').hasClass('username'));
console.log(filteredElem.length)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<label for="username">Username</label>
<input class="form-control username" type="text" placeholder="Username" id="username" />
</div>
<div>
<label for="Password">Password</label>
<input class="form-control password" type="password" placeholder="Password" id="password" />
</div>
<div style="text-align:center;">
<button id="login">Login</button>
</div>
</div>
Firstly note that you're calling the jQuery filter() method, not the native array filter() method as your title implies. This is because elem holds a jQuery object, not an array.
The issue itself is because the first argument passed to the jQuery filter() handler function is the index of the current element, not a reference to the element itself. As such you need to change the logic to:
var filteredElem = elem.filter((i, div) => ...
$('#login').click(function() {
var elem = jQuery(this).parent('div').siblings('div:has(input)');
var filteredElem = elem.filter((i, div) => jQuery(div).children('input').hasClass('username'));
console.log(filteredElem.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<label for="username">Username</label>
<input class="form-control username" type="text" placeholder="Username" id="username" />
</div>
<div>
<label for="Password">Password</label>
<input class="form-control password" type="password" placeholder="Password" id="password" />
</div>
<div style="text-align:center;">
<button id="login">Login</button>
</div>
</div>
That being said, you can simplify this example to just use find() instead of explicitly looping through all the sibling divs:
$('#login').click(function() {
var $username = $(this).parent('div').siblings('div:has(input)').find('.username');
console.log($username.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<label for="username">Username</label>
<input class="form-control username" type="text" placeholder="Username" id="username" />
</div>
<div>
<label for="Password">Password</label>
<input class="form-control password" type="password" placeholder="Password" id="password" />
</div>
<div style="text-align:center;">
<button id="login">Login</button>
</div>
</div>
Even simpler still would be to use the submit event of your login form and then find() the .username within that:
$('#yourLoginForm').on('submit', function() {
var $username = $(this).find('.username');
});

Passing the value from a few text fields into a third (generating a username) HTML, JS

So a trying to pass the values from two text field to the third and I know it should be correct but it won't work. Would you know where is the problem? Thanks
<div class="form-group">
<label for="ime">Ime:</label>
<input type="text" class="form-control" id="ime" name="ime">
</div>
<div class="form-group">
<label for="prezime">Prezime:</label>
<input type="text" class="form-control" id="prezime" name="prezime">
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" onclick="kreiraj_username()">
</div>
<script>
function kreiraj_username() {
var ime = document.getElementById("ime").value.toLowerCase();
var prezime = document.getElementById("prezime").value.toLowerCase();
// var id_clan = document.getElementById("id_clan").value;
var username = document.getElementById("username").value.toLowerCase();
username = ime + prezime;
}
</script>
You need to assign to the value of the username element, because primitive values are not passed by reference in Javascript. If you assign a variable to a primitive taken from an object, in order to update the object after changing the variable, you need to explicitly assign the the object's property again.
But in this case, since the original username value isn't being used, just assign to the field's value directly:
function kreiraj_username() {
var ime = document.getElementById("ime").value.toLowerCase();
var prezime = document.getElementById("prezime").value.toLowerCase();
document.getElementById("username").value = ime + prezime;
}
<div class="form-group">
<label for="ime">Ime:</label>
<input type="text" class="form-control" id="ime" name="ime">
</div>
<div class="form-group">
<label for="prezime">Prezime:</label>
<input type="text" class="form-control" id="prezime" name="prezime">
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" onclick="kreiraj_username()">
</div>

Auto submit form information without page reload

I have a form with a bunch of number fields, all these fields serves the purpose to be added to each other through php. The only problem is that for the numbers to actually be submitted and make the php function work, I have to click the submit button which reloads the page. While this actually does work it is a bit annoying, that it has to reload and at the same time it removes the numbers from the actual form, so the user can't see where he/she has entered their numbers.
I know it is possible in some way to make it submit automatically, but is it possible to make the php function get the form information every time a user enters something, so that the new total sum would be automatically updated, thus not having to reload?
I have my php and html in the same script, but for the case of this question I have split them into two parts.
PHP part
<?php
$amount_s_bp = $_POST['amountSmallBP'];
$amount_m_bp = $_POST['amountMedBP'];
$amount_l_bp = $_POST['amountLargeBP'];
$amount_xl_bp = $_POST['amountXLBP'];
$amount_s_wp = $_POST['amountSmallWP'];
$amount_m_wp = $_POST['amountMedWP'];
$amount_l_wp = $_POST['amountLargeWP'];
$amount_xl_wp = $_POST['amountXLWP'];
$amount_s_bs = $_POST['amountSmallBS'];
$amount_m_bs = $_POST['amountMedBS'];
$amount_l_bs = $_POST['amountLargeBS'];
$amount_xl_bs = $_POST['amountXLBS'];
$amount_s_bt = $_POST['amountSmallBT'];
$amount_m_bt = $_POST['amountMedBT'];
$amount_l_bt = $_POST['amountLargeBT'];
$amount_xl_bt = $_POST['amountXLBT'];
$shirt_price = 150;
$amount_total = $amount_s_bp + $amount_m_bp + $amount_l_bp + $amount_xl_bp + $amount_s_wp + $amount_m_wp + $amount_l_wp + $amount_xl_wp + $amount_s_bs + $amount_m_bs + $amount_l_bs + $amount_xl_bs + $amount_s_bt + $amount_m_bt + $amount_l_bt + $amount_xl_bt;
$price_total = $amount_total * $shirt_price;
?>
Form part
As you can see I have a bunch of number inputs and then at the end I have a "total" area where the total sum should be displayed using <?php echo $price_total; ?> and <?php echo $amount_total; ?>.
<form action="index.php" method="post" id="orderForm" onsubmit="return checkCheckBoxes(this);">
<div class="row">
<div class="col-xs-6">
<div class="bpShirtDesign">
<span id="bpShirtOformT">Sort Polka</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBP" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBP" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBP" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBP" placeholder="Antal"/>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="wpShirtDesign">
<span id="bpShirtOformT">Hvid Polka</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallWP" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedWP" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeWP" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLWP" placeholder="Antal"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="bsShirtDesign">
<span id="bpShirtOformT">Bla Stribet</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBS" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBS" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBS" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBS" placeholder="Antal"/>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="btShirtDesign">
<span id="bpShirtOformT">Bla Tattersall</span><br>
<span id="sBP">Small</span>
<div id="firstName">
<input type="number" id="amount" name="amountSmallBT" placeholder="Antal"/>
</div>
<span id="mP">Medium</span>
<div id="firstName">
<input type="number" id="amount" name="amountMedBT" placeholder="Antal"/>
</div>
<span id="lBP">Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountLargeBT" placeholder="Antal"/>
</div>
<span id="xlBP">X-Large</span>
<div id="firstName">
<input type="number" id="amount" name="amountXLBT" placeholder="Antal"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="bgTotals">
<input type="submit" value="Submit" id="submitValues">
<span id="totalAmount" class="h3">I alt antal = </span><?php echo $amount_total; ?><br>
<span id="totalPrice" class="h3">I alt pris = </span> <?php echo $price_total; ?><span> DKK</span>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</form>
You don't need a server-side script for this kind of processing. Just prevent that the form is submitted with:
<button type="button">Button</button>
Then, using javascript, retrieve the value of each form and perform calculations.
//Gets the value
var value = document.getElementById('myid')
//Repeat that last line until all values are retrieved
...
//Make your calculations
var result = value + value2 //... etc
//Display your result
document.getElementById('resultid').textContent = result;
Although, if you are going to sum a lot of elements, it might be better to give the same class to those elements, so you can do this:
var elements = document.getElementsByClassName('myclassname');
var sum = 0;
for (var i=0, max=elements.length; i < max; i++) {
sum = sum + parseInt(elements.item(i).textContent);
}
UPDATE
To add an event listener to every input you can iterate over every element or you could associate a listener to a parent element like this:
document.getElementById('myParentElement').addEventListener('input', function() {
return update();
}, false);
And you should throw all the code that retrieves the values from the inputs, perform the calculations and updates the DOM in the update() function, which will get called every time an input changes.
First things first, you have the id "amount" on all of your inputs. This will not work, an id can only be used once per page. So, figure out a convention to make these id's unique. Like id='field1-id' or something. Also, remove the action and method attributes from your form tag. They'll be unneeded at this point.
Then you can use jQuery and an AJAX call to do what you are looking for. Something like:
$("#submitValues").bind('click', function(e){
var formData[];
$("#orderForm").each('input[^="-id"]', function(){
formData.push($(this).val());
});
$.ajax({
url: 'index.php',
data: formData
}).success(function(response){
$("totalAmount").val(response.returnedTotalAmount);
$("totalPrice").val(response.returnedTotalPrice);
}).fail(function(response){
/* do something else */
});
e.preventDefault();
});
Mind you this code is untested, and very hastily written but it should give you the general idea of how to accomplish what you're after.

only execute function with ng-click if input fields are not empty

I only want to perform this function if the other two fields are not empty, not sure how to do it.
ng-click="saveToList($event)"
HTML
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
Post
</div>
app.js
$scope.saveToList = function(event) {
var mvName = $scope.mvName.trim();
var mvUrl = $scope.mvUrl.trim();
if (mvName.length > 0) {
$scope.favUrls.$add({
name: mvName,
title: mvUrl
});
urlName.value = ''; //urlName is the ID of input box - Angular rocks!
urlLink.value = ''; //urlName is the ID of input box - Angular rocks!
}
}
I get this error when they are empty:
Error: $scope.mvName is undefined
The problem isn't anything to do with Angular: .trim() doesn't work against undefined values. Check to see if the variable is defined before trying to trim it, for example:
var mvName = ($scope.mvName) ? $scope.mvName.trim() : '' ;
You should initialize $scope.mvName in your controller! As it is empty, you are getting an error at line var mvName = $scope.mvName.trim();
EDIT
Post
You can add ng-disabled directive to your a tag. Something like this:
<a href ng-disabled="!mvName || !mvUrl" ng-click="saveToList($event)" class="btn btn-block post">Post</a>
or check that vars in your js:
$scope.saveToList = function(event) {
if(!$scope.mvName || !$scope.mvUrl)
return;
var mvName = $scope.mvName.trim();
var mvUrl = $scope.mvUrl.trim();
...
You could do it like this:
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
<a href="javascript:"
ng-click="(mvName != '' && mvUrl != '') && saveToList($event)" class="btn btn-block post">Post</a>
</div>
Or use ng-disabled="mvName === '' && mvUrl === ''"
Other options would be to not render the button: ng-if or ng-show.
How about performing a simple check to see if the fields are empty or not, before you perform any comparisons using the value. That should solve the issue I believe.
<form name="myForm">
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" required class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" required class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
Post
</div>
</form>
Try using the angular validation.

How do I get the value of a child on clicking another child of a parent Class?

consider I have such a structure(a group of fields which repeat);
<div class="form-group Row"> <!-- first row-->
<div class="col-sm-3">
<input type="text" class="form-control User" name="user" value="$users" placeholder="Username" />
</div>
<div class="col-sm-3">
<input type="password" class="form-control" name="pw" value="$passwords" placeholder="Password" />
</div>
<a class="delete" onclick='//do something'><img src="delete.png"></a>
</div>
<div class="form-group Row"><!-- second row-->
<div class="col-sm-3">
<input type="text" class="form-control User" name="user" value="$user" placeholder="Username" />
</div>
<div class="col-sm-3">
<input type="password" class="form-control" name="pw" value="$passwords" placeholder="Password" />
</div>
<a class="delete" onclick='//do something'><img src="delete.png"></a>
</div>
when I click on the delete-image of any Row, I want to get the value of the input field with class name "User" of this specific Row.
How can I do this in javascript?
If you use jQuery you don't need use inline events, you can add events with .on function, and get value like in example
$('.delete').on('click', function () {
var value = $(this).parent().find('.User').val();
console.log(value)
});
Example
Try as follows:
$('.delete').on('click', function(){
var value = $(this).closest('.row').find('.User').val();
//Do something with value;
});
In vanilla JS your "do something" will be like this:
alert( this.parentNode.getElementsByClassName("user")[0].value; )

Categories

Resources