Knowing what button is pressed in Javascript - javascript

I was wondering if there was a way I could ask if a certain button was pushed so that it would do a certain thing in the function. I know I could split this up into two separate functions, but I want to know how to do this this way.
I'll put my code below.
function displaySort(form) {
var list = form.values.value.replace(/\s+/g, '')
list = list.split(/,/)
if (document.getElementById("fSort").form.input.id) {
list.sort()
var listAsString = list.join(", ")
form.sortedDisplay.value = listAsString
} else if (document.getElementById("rSort").form.input.id) {
list.sort(reverseCompare)
var listAsString = list.join(", ")
form.reverseSortedDisplay.value = listAsString
}
window.alert("Messed Up");
}
function reverseCompare(s1, s2) {
if (s1 < s2) {
return +1
} else if ( s1 == s2 ){
return 0
} else {
return -1
}
}
the form:
<form>
<table>
<tr>
<td>
<input type="text" name="values" value=" Bob, Ted, Carol,
Bette, Alice, Peter "
onclick="if (this.value == this.defaultValue) this.value=''"
size="80"
/>
<input type="button"
onclick="displaySort(this.form)"
value="Sort"
id="fSort"
/>
<input type="button"
onclick="displaySort(this.form)"
value="Reverse Sort"
id="rSort"
/>
<input type="reset"
value="Reset Form"
/>
</td>
</tr>
<tr>
<td>
<input type="text" name="sortedDisplay" value="Sorted list will show here"
size="35"
readonly
style="font-size:24pt;font-weight:normal;"
/>
</td>
</tr>
<tr>
<td>
<input type="text" name="reverseSortedDisplay"
value="Reverse sorted list will show here"
size="35"
readonly
style="font-size:24pt;font-weight:normal;"
/>
</td>
</tr>
</table>
</form>

Add another parameter to the function button:
function displaySort(form, button)
{ ...
And pass the button reference to it when clicked:
<input type="button"
onclick="displaySort(this.form, this)"
value="Reverse Sort"
id="rSort"
/>

Related

hide last element of an array

How to hide the last index of an array as I want to hide the label and show the input when user clicks on add button . Couldn't find help . Here is my code:-
<tr ng-repeat="personalDetail in personalDetails">
<td>
<label ng-show="lab[$index]=true" for="settings" > {{personalDetail.Sname}}</label>
<input ng-show="lab[$index]=false" type="text" ng-model="personalDetail.Sname" />
</td>
<input type="button" class="btn btn-primary addnew pull-right btn-space" ng-click="addNew($index)" value=" Add New">
And my angular code :
$scope.addNew = function(val) {
$scope.personalDetails.push({
'Sname': "",
'Settings': "",
});
var ind = $scope.personalDetails.length - 1;
$("label[data-val='" + ind + "']").hide();
$("input[data-val='" + ind + "']").show();
$scope.PD = {};
};
try this
<tr ng-repeat="personalDetail in personalDetails">
<td>
<label ng-hide="$last" for="settings" > {{personalDetail.Sname}}</label>
<input ng-show="$last" type="text" ng-model="personalDetail.Sname" />
</td>
<tr>
Reference: ngRepeat
Just check for $last,
<td>
<label ng-show="lab[$index]==true" for="settings"> {{personalDetail.Sname}}</label>
<input ng-show="lab[$index]==false" type="text" ng-model="personalDetail.Sname" />
</td>

How do I assign value of the clicked button

I have the following on jsfiddle. What I need to accomplish is when I click on a button the respective value is inserted in the blank.
https://jsfiddle.net/aminbaig/jefee77L/
Here is the Code:
HTML:
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change()" />
<input type="submit" id="byBtn1" value="Truck" onclick="change()" />
<input type="submit" id="byBtn2" value="Trash" onclick="change()" />
Javascript:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}
You can do like this
JS
get the value of the button from the function parameter
function change(value) {
var title = document.getElementById('title');
title.innerHTML = value;
}
HTML
change button type='submit' to type='button', Also pass the value as the function parameter
<input type="button" id="myTextField" value="something" onclick="change(this.value)" />
<input type="button" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="button" id="byBtn2" value="Trash" onclick="change(this.value)" />
DEMO
use like this onclick="change(this.value)" .send the value of the input via click function
function change(val) {
if (val.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = val;
}
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change(this.value)" />
<input type="submit" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="submit" id="byBtn2" value="Trash" onclick="change(this.value)" />

how to select multiple checkbox validation in javascript

Here is my Form. I need validation in JavaScript.
At least one checkbox selected in validation.
I hop you all are understand what I need.
please give me solution for that.
If any query then feel free ask.
<form action="#" method="post" name="studentregistration" onsubmit="return(validate());">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" value="Chess" id="hobby">Chess
<input type="checkbox" name="hobby" value="Music" id="hobby">Music<br>
<input type="checkbox" name="hobby" value="Cricket" id="hobby">Cricket
<input type="checkbox" name="hobby" value="Reading" id="hobby">Reading
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
If you're trying to validate that at least one checkbox is checked, then this should work for you using jQuery:
$('input[type="checkbox"]:checked').length > 0
In "pure" js, you could remove the onsubmit attribute and do this instead:
document.querySelector('form[name="studentregistration"]').onsubmit = function(e) {
e.preventDefault();
var cbx = document.querySelectorAll('form[name="studentregistration"] input[name="hobby"]:checked');
if(cbx.length > 0) {
// at least one checked - do something
}
else {
// none checked
}
}
See a live demo!
Complete solution.
In order to submit the form after validation you must use:
document.getElementById("myForm").submit();
document.getElementById("submitform").addEventListener("click",submit_form);
function submit_form(e){
var ob = "";
var chess = document.getElementById("hobby1").checked;
var music = document.getElementById("hobby2").checked;
var cricket = document.getElementById("hobby3").checked;
var reading = document.getElementById("hobby4").checked;
if(chess == true){
ob += "hobby: chess selected!\n";
}
if(music == true){
ob += "hobby: music selected!\n";
}
if(cricket == true){
ob += "hobby: cricket selected!\n";
}
if(reading == true){
ob += "hobby: reading selected!\n";
}
if(ob==""){
alert("No hobbys selected");
}
else{
alert(ob);
//document.getElementById("myForm").submit();
}
//for testing purposes
e.preventDefault();
return false;
}
<form id = "myForm" action="#" method="post" name="studentregistration">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" id="hobby1">Chess
<input type="checkbox" name="hobby" id="hobby2">Music<br>
<input type="checkbox" name="hobby" id="hobby3">Cricket
<input type="checkbox" name="hobby" id="hobby4">Reading
</td>
</tr>
<tr>
<td>
<input type="button" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
if($("#hobby").is(':checked')){
alert("checkbox checked");
}
else{
alert("Please select at least one checkbox");
}
Here is another easy answer
var test = document.getElementsByName("hobby[]");
if(test[0].checked==false && test[1].checked==false && test[2].checked==false && test[3].checked==false)
{
alert("Please Check");
return false;
}

JavaScript uncaught reference error using onclick attribute in input form tag

JavaScript Function
function submitToServer(formObject)
{
if(validateUserName(formObject["userName"]) && validatePassword(formObject["password"]))
{
formObject.submit();
}
}
HTML FORM FIELD
<form method="POST" action="SignIntoPortal">
<table>
<tr>
<td> User Name : </td>
<td>
<input type="text" id="userName" name="userName" onblur="validateUserName(this)">
<span id="userName_help" />
</td>
</tr>
<tr>
<td> Password : </td>
<td>
<input type="password" id="password" name="password" onblur="validatePassword(this)">
<span id="password_help" />
</td>
</tr>
<br>
</table>
<input type="button" name="submitButton" id="submitButton" value="Submit" onclick="submitToServer(this.form);">
</input>
</form>
The above is my code, which validates data and submits the form. but i keep getting
Uncaught ReferenceError: submitToServer is not defined
error, which I am unable to resolve. what could be the reason?
But, when I tried it with different form it worked with different names and fields.
EDIT
the difference between the code that worked and this is that, the former code does not use table it works smooth. Does scope change with table ?
You can find the code here CODE FIDDLE
You can get .html file here
SignIn.html
<html>
<head>
<title>Sign into Shopping Zone</title>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-8">
<style>
body
{
font: 14px verdana;
}
h1
{
font: arial-black;
color: blue;
}
</style>
<script type="javascript" language="text/javascript">
function submitToServer(formObject)
{
if(validateUserName(formObject["userName"]) && validatePassword(formObject["password"]))
{
formObject.submit();
}
}
function validateUserName(inputField)
{
if(inputField.value.length == 0)
{
document.getElementById("userName_help").innerHTML = "Please enter value";
return false;
}
else
{
document.getElementById("userName_help").innerHTML = "";
return true;
}
}
function validatePassword(inputField)
{
if(inputField.value.length == 0)
{
document.getElementById("password_help").innerHTML = "Please enter value";
return false;
}
else
{
document.getElementById("password_help").innerHTML = "";
return true;
}
}
</script>
</head>
<body>
<h1><b><i>Shopping Zone</i></b></h1>
<p> Kindly Provide Login info
</p>
<!-- SignIn Form Data for Passing to SignIntoPortal-->
<form method="POST" action="SignIntoPortal">
<table>
<tr>
<td> User Name : </td> <td><input type="text" id="userName" name="userName" onblur="validateUserName(this)"><span id="userName_help" /></td>
</tr>
<tr>
<td> Password : </td> <td><input type="password" id="password" name="password" onblur="validatePassword(this)"><span id="password_help" /></td>
</tr>
<br>
</table>
<input type="button" name="submitButton" id="submitButton" value="Submit" onclick="submitToServer(this.form)"></input>
</form>
</body>
</html>
in the script header, your 'type' and 'language' attributes are mixed up. type should be 'text/javascript' and language should be 'javascript' although the language attribute is not required
<script type="text/javascript" language="javascript">

calculate form values from radio group

Trying to calculate a selection value from a radio group and values from other fields. Any 'Name' input adds a value to the Total. I need the value from the radio group to be added to that total.
Here is the HTML:
<FORM NAME="testauthorization" ACTION="" METHOD=POST id="exhibitreg">
<table>
<tr>
<td><label>
<input type="radio" name="sponsorship" value="3000" id="sponsor1" />
$3,000</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1500" id="sponsor2" />
$1,500</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1000" id="sponsor3" />
$1,000</label>
<br /></td>
</tr>
<tr>
<td>Name 1 <INPUT NAME="Name_1" TYPE="TEXT" id="name1" onchange="updatecost(1, 50)" onkeyup="updatecost(1, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_1" TYPE="TEXT" VALUE="" size="4" id="cost1"></td>
</tr>
<tr>
<td>Name 2<INPUT NAME="Name_2" TYPE="TEXT" id="name2" onchange="updatecost(2, 50)" onkeyup="updatecost(2, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_2" TYPE="TEXT" VALUE="" size="4" id="cost2"></td>
</tr>
<tr>
<td>Name 3<INPUT NAME="Name_3" TYPE="TEXT" id="name3" onchange="updatecost(3, 50)" onkeyup="updatecost(3, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_3" TYPE="TEXT" VALUE="" size="4" id="cost3"></td>
</tr>
<tr>
<td colspan="4">Total:
<INPUT NAME="Total" id="Total" TYPE="TEXT" VALUE="" size="8" onFocus="this.form.elements[0].focus()" >
<INPUT TYPE="HIDDEN" onchange="totalcost()" onkeyup="totalcost()"></td>
</tr>
</table>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<input type="RESET" name="Reset" value="Reset" />
</FORM>
And here is the JS:
<script language="JavaScript" type="text/javascript">
function getRadioValue(name) {
var group = document.getElementsByName('sponsorship');
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.getElementById("cost" + num);
if (!text) return;
if (!cost) return;
if (text.value == "") {
cost.value = "";
}
else {
cost.value = dollars;
}
totalcost();
}
function totalcost() {
var total = 0;
for (var i = 1; i <= 3; i++) {
var cost = document.getElementById("cost" + i);
if (cost.value) total += Number(cost.value);
}
document.getElementById("Total").value = total;
}
//-->
</script>
What am I missing? By the way, in case it is not clear, I am a JS novice, so I fully accept criticism that helps me understand a more fundamental error in my approach. Simple is best for me: ;-) Thank you in advance.
Change below function in place of existing
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.querySelector('input[name="sponsorship"]:checked');
if (!text) return;
if (!cost) return;
totalcost(cost);
}
function totalcost(cost) {
var total = 0;
for (var i = 1; i <= 3; i++) {
var text1 = document.getElementById("name" + i);
if (text1.value != "") total += Number(cost.value);
}
document.getElementById("Total").value = total;
}

Categories

Resources