jQuery - What is the good way to implement continouns ranking - javascript

Suppose I have 4 input fields now:
<table>
<tr><th></th><th>Factor 1</th></tr>
<tr><td>Company A</td><td><input type="text" name="text1" id="text1"></td></tr>
<tr><td>Company B</td><td><input type="text" name="text2" id="text2"></td></tr>
<tr><td>Company C</td><td><input type="text" name="text3" id="text3"></td></tr>
<tr><td>Company D</td><td><input type="text" name="text4" id="text4"></td></tr>
</table>
The inputs are integer from 1 to 4 uniquely in each input field. It is like a ranking for which Company is the best for this Factor, and which is the second and so on.
For example:
When we input 1, 3, we alert 2 is missing in the ranking.
When we input 1, 2, 4, then we alert 3 is missing.
Inputs are not required, but when there are inputs, the sequence must from 1 to 4.
Here is the code I tried.
function checkMissingRank(object){
object.change(function() {
var max = 0;
var actSum = 0;
var rows = object.length;
for(var i=1 ; i<=rows ; i++){
if($('#text'+i+'').val() != ""){
var actVal = parseInt($('#text'+i+'').val());
//alert("actVal: "+actVal);
actSum = actSum + actVal;
if(actVal>max){
max=actVal;
//alert("max: "+ max);
}
}
}
//alert("actSum: "+ actSum);
totalSum = ((1+max)*max)/2;
//alert("totalSum: "+ totalSum);
var missVal = totalSum - actSum;
//alert("missVal "+ missVal);
if(missVal != 0){
alert("Ranking "+missVal+" is missing.");
}
});
}
checkMissingRank($('input[name^="text"]'));
It is working fine when just one Value missing (1 missing from 1 ,2 ,3, 4). But when 1, 2 both missing, it return 3 is missing which is the sum of 1 and 2. Is there a better way to do this?

HTML :
<input type="text" name="text1" id="text1">
<input type="text" name="text2" id="text2">
<input type="text" name="text3" id="text3">
<input type="text" name="text4" id="text4">
<input type="button" id="btnTest">
and Jquery:
$("#btnTest").click(function() {
$('input[type=text]').each(function() {
var msg = $(this).prop("id");
if ($(this).val() == "") {
switch (msg) {
case ("text1"):
alert('miss 1');
break;
case ("text2"):
alert('miss 2');
break;
case ("text3"):
alert('miss 3');
break;
case ("text4"):
alert('miss 4');
break;
}
}
})
});
Fiddle Sample https://jsfiddle.net/shree/5ucxau2n/1/
I create a sample on button click.Hope its help.

This alerts each input that is missing.
$(function(){
$("button").on("click", function(){
$("input").each(function(){
if($(this).val() == ""){
alert($(this).attr("id") + " is missing");
}
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input type="text" name="text1" id="text1">
<input type="text" name="text2" id="text2">
<input type="text" name="text3" id="text3">
<input type="text" name="text4" id="text4">
</form>
<button>Enter</button>
This is if you just want a list of all the input elements that are missing. Only one alert box:
$("button").on("click", function(){
var str = ""
$("input").each(function(){
if($(this).val() == ""){
str += $(this).attr("id") + " and "
}
})
alert(str + " is missing");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input type="text" name="text1" id="text1" placeholder = "type 1">
<input type="text" name="text2" id="text2" placeholder = "type 2">
<input type="text" name="text3" id="text3" placeholder = "type 3">
<input type="text" name="text4" id="text4" placeholder = "type 4">
</form>
<button>Enter</button>
Any Questions? let me know.

Related

Adding input fields together and displaying in a label

I'm writing a program to add tests, exams, practicals, assignments to a module.
With regards to the course weighting I was wondering if you could dynamically change the value of the total weighting when a user enters a weighting per task.
Like this:
Problem
The inputs in the red rectangle should be added up and displayed in the blue rectangles label.
In turn, the blue rectangle should be added up and displayed in the green rectangles label.
Any help will be appreciated please
I have tried this so far:
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="fnum" size="35" id="first">
+ Second Number:
<input type="text" name="snum" size="35" id="sec">
+ Third Number:
<input type="text" name="lom" size="35" id="third3">
<br>
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<button type="button" onclick="Calculate();">Calculate</button>
<script lang="javascript">
function Calculate() {
var first = document.getElementById('first').value;
if(document.getElementById('sec'))
{
var last = document.getElementById('sec').value;
}
else
{
var last = 0;
}
if(document.getElementById('third'))
{
var third = document.getElementById('third').value;
}
else
{
var third = 0;
}
document.getElementById('ans').value = parseInt(first) + parseInt(last) + parseInt(third);
document.form1.submit();
}
https://jsfiddle.net/www1fxjb/9/
What I am asking is to change the label as soon as the numbers change in the input fields.
You need to use the onchangeevent in your input fields properties.
You can then point your onchangeevent to your calculate method.
Also, add default values of "0" in your input fields so that it will always have a value to add and this will prevent errors.
<input type="number" name="fnum" size="35" id="first" onchange="Calculate();" value="0"/>
+ Second Number:
<input type="number" name="snum" size="35" id="second" onchange="Calculate();" value="0"/>
+ Third Number:
<input type="number" name="lom" size="35" id="third" onchange="Calculate();" value="0"/>
<br />
Answer:
<input type="text" name="ans" size="35" id="ans" />
Javascript:
<script lang="javascript">
function Calculate() {
if (document.getElementById('first')) {
var first = document.getElementById('first').value;
}
else {
var first = 0;
}
if (document.getElementById('second'))
{
var second = document.getElementById('second').value;
}
else
{
var second = 0;
}
if (document.getElementById('third'))
{
var third = document.getElementById('third').value;
}
else
{
var third = 0;
}
document.getElementById('ans').value = parseInt(first) + parseInt(second) + parseInt(third);
document.form1.submit();
}
</script>
Hope it helps.

check atleast 2 of 5 input fields were not empty

How to check of two out of five inputted fields and get the value? I'm using jQuery, and I'm not sure what is the proper positioning of this code. Maybe you guys can help me.
Here is my code:
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
}
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
The result that I get is that it only trigger the res variable if the execution reach into 2 above.
I want to submit the form only when there are at least two fields were inputted.
Thanks!
You're checking if any value other than the first two has value
The correct way to implement your check would be:
$(document).ready(function(){
$("#btnSubmit").on('click', function(){
var val = $(".validate");
var res = "";
var reqCount=0
for(var i = 0; i < val.length; i++){
if(val[i].value){
reqCount++;
}
if(reqCount >= 2){
res = "Code Execution here";
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
I don't know why there's a C# tag on this question, if you mean to do this on the server side, that'd be a whole different question
Change you logic to count number of filed having value in for loop
than base don count change alert message
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = ""; let count=0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
count++;
}
}
if (count >= 2) {
res = "Code Execution here";
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
If all you want to do is make sure you have atleast 2 feilds filled before the user submits the form , you can do the below:
function isEmpty(validateElem) {
return (validateElem === "" || typeof validateElem === 'undefined') ? true : false;
}
$(function(){
var InputValidateCount = 0;
$('form').submit(function(){
$('input').each(function(e , i){
if(!isEmpty($(this).val())) {
InputValidateCount++;
}
});
if(InputValidateCount < 2) {
return false; // Stop from from submitting;
}
});
});
You should count the validated fields before submission.
Upvote if this answered you. :P
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var minimumNonEmptyFields = 2;
var validatedNonEmptyFieldsCount = 0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
validatedNonEmptyFieldsCount++;
}
}
if(validatedNonEmptyFieldsCount >= minimumNonEmptyFields) {
alert( validatedNonEmptyFieldsCount + " fields are non-empty");
} else {
alert("Please fill " + (minimumNonEmptyFields - validatedNonEmptyFieldsCount) + " more fields");
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>
Validate any 2 input
</title>
</head>
<body>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<input type="text" class="validate" id="req6" name="req6">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
<script></script>
</body>
</html>
if atleast two input is not empty then return true else return false .
if return's true it submit's the form else it will not.
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
console.log("success");
return true;
}
}
}
console.log("fail");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>

How to determine if the input is of array type in javascript?

<input type="text" name="members[0].name">
<input type="text" name="members[0].address">
Javascript code :
var input_text;
var inputs=document.querySelectorAll("input[type=text],textarea, select");
_.each(inputs, function(e, i) {
var keyName = $(e).attr("name");
if (typeof keyName != "undefined") {
var text = $(e).parent().find('label').text();
if ($(e).is('select')) {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).find(':selected').text() + "</td></tr>";
}
else {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).val() + "</td></tr>";
}
}
});
console.log(input_text);
As You can see, I m getting the values of all the inputs in $(e).val() except those above mentioned inputs.
Those inputs aren't an "array" in the browser. They just use a naming convention in their name which is used by some server-side handling (for instance, in PHP) to organize the form data for you when it's submitted.
I don't know what you mean by "previewing," but you can see the values of those elements by simply looping through the elements of your form (yourForm.elements), or by using yourForm.querySelectorAll("input[type=text]") (or $(yourForm).find("input[type=text]") using jQuery — I missed the jquery tag on your question at first).
Example of theForm.elements:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.elements, function(element) {
if (element.type === "text") {
console.log(element.name + " = " + element.value);
}
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of theForm.querySelectorAll:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.querySelectorAll("input[type=text]"), function(element) {
console.log(element.name + " = " + element.value);
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of $(theForm).find:
$("form input[type=button]").on("click", function() {
var form = document.getElementById("the-form");
$(form).find("input[type=text]").each(function() {
console.log(this.name + " = " + this.value);
});
// Of course, we could have just used `$("#the-form input[type=text]").each`...
// but I was assuming you'd already have `form`
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So many ways to get the input type values using formID
$('#formId input, #formId select').each(
function(index){
var input = $(this);
}
);
OR
var formElements = new Array();
$("form :input").each(function(){
formElements.push($(this));
});
OR
var $form_elements = $("#form_id").find(":input");
hope it helps you.
You can use serializeArray or serialize for it .
$("form").serializeArray();
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Doc

I want to show alert message

This is running good, but i want to show alert message if sum of all input value not equal to hundred and stop on same page.
function doMath(){
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
document.write(sum);
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Here is another solution
function _get(ID){
return document.getElementById(ID);
}
function doMath(){
var my_input1 = _get('my_input1').value ? parseInt(_get('my_input1').value) : 0;
var my_input2 = _get('my_input2').value ? parseInt(_get('my_input2').value) : 0;
var my_input3 = _get('my_input3').value ? parseInt(_get('my_input3').value) : 0;
var my_input4 = _get('my_input4').value ? parseInt(_get('my_input4').value) : 0;
var my_input5 = _get('my_input5').value ? parseInt(_get('my_input5').value) : 0;
var my_input6 = _get('my_input6').value ? parseInt(_get('my_input6').value) : 0;
// Add them together and display
var sum = my_input1 + my_input2 + my_input3 + my_input4 + my_input5 + my_input6;
if(sum==100){
alert('Sum is = 100');
/*YOUR CODE HERE*/
}else if(sum<100){
alert('Sum is less than 100');
/*YOUR CODE HERE*/
}else if(sum>100){
alert('Sum is bigger than 100');
/*YOUR CODE HERE*/
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Here is the details about Conditional (ternary) Operator
If I clearly understood what you want, you can try this:
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if (sum != 100) {
alert('Different from a hundred')
return false;
}
I used return false in case you want to handle the result and take some other action.
You can use alert() function to display alert popup
if(sum!=100){
alert("Sum is not equal to 100");
}else{
document.write(sum);
}
Please refer working snippet
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if(sum!=100){
alert("Sum is not equal to 100");
}else{
document.write(sum);
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Replace
document.write(sum);
with
if(sum==100) {
document.write(sum);
} else {
alert("show your messaage");
}
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if(sum >= 100){
document.write(sum);
}
else{
alert("sum is less than 100")
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />

Trying to get all input value into string, jquery or javascript

I am trying to use jquery or javascript get all input value into a string (1,2,3,4) and ignore empty value. Thank you.
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>
// string to keep the result
var output = "";
// iterate over all inputs with class 'as_sym' inside the '#sym_form'
$('#sym_form > input[class=as_sym]').each(function(){
// only inputs with non-empty values
if ($(this).val() != "") {
// the first value doesn't have a comma in front of it
// subsequent values do have a comma in front of them
if (output == "") {
output += $(this).val();
} else {
output += "," + $(this).val();
}
}
});
// here do whatever you want with the 'output' variable
const form = document.getELementById("sym_form");
for (var element of form.elements) {
if(element.nodeName === "INPUT" && element.value) {
// do something with element.value
}
}
var $inputs = $('#sym_form .as_sym');
var result ="";
$.each($inputs, function(i, v) {
var val = $(this).val();
result += val;
});
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>
<p id="result"></p>
You can use .querySelectorAll() to select all "#sym_form .as_sym" elements, Array.prototype.forEach(), Function.prototype.call() to attach input event to each element, at input event concantenate values of each "#sym_form .as_sym" element to a string, use .split(), .join() to include comma , character between each character or resulting string
var inputs = document.querySelectorAll("#sym_form .as_sym");
Array.prototype.forEach.call(inputs, function(input) {
input.addEventListener("input", function(e) {
for (var i = 0, val = "", len = inputs.length; i < len; i++) {
val += inputs[i].value;
}
console.log(val.split("").join(","))
})
})
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>

Categories