Jquery condition doesnt work - javascript

I must be doing some very basic mistake, because i cant get to result2, even though it checks the condition for it. it detects the counter and InpActive, but it only add up the counter once (but that should be enough to check for condition 2) nor perform the check for the test2 condition.
Edit: im presenting the full function. I want to make a mysqli query with each input, and i want to be able to add and take out each entry, preserving the query structure to be sent to the server. Its not working for some reason. In this post, im not adding the PHP part. Im only interested in making the jquery part work.
This is the jquery code:
var inpreco = ["", "", ""];
var altpreco = ["", "", ""];
var inprocess = ["", "", ""];
var altprocess = ["", "", ""];
var cpcounter8 = 0;
var cpcounter9 = 0;
$(".opcaopreco").click(function () {
SuperFun(this, "#preco", inpreco, altpreco, "altpreco2", "cpvalor",
"cpindex", "cpactivo", cpcounter9, "preco", "1 AND 5000");
});
$(".opcaopreco2").click(function () {
SuperFun(this, "#process", inprocess, altprocess, "altprocess2",
"cpvalor8", "cpindex8", "cpactivo8", cpcounter8, "process", "1 AND 11");
});
function SuperFun(element, input, inpArray, secArray, secArray2, inpValue,
secIndex, inpActive, counter, msqlip, ending) {
var inpValue = $("#" + element.id).val();
var secIndex = $("#" + element.id).data(secIndex);
var inpActive = $("#" + element.id).data(inpActive);
if (counter==0){
counter++;
$("#" + element.id + "l").addClass("activa");
$(element).data(inpActive, "primary");
inpArray[0] = (inpValue);
}else
if (inpActive=="") {
counter++;
$("#" + element.id + "l").addClass("activa");
$(element).data(inpActive, "yes");
inpArray[secIndex]=(" OR "+msqlip+" BETWEEN "+inpValue);
secArray[secIndex]=(secIndex);
}else
if (inpActive=="yes") {
counter--;
$("#" + element.id + "l").removeClass("activa");
$(element).data(inpActive, "");
inpArray[secIndex]="";
secArray[secIndex] = "";
}else
if (inpActive=="primary" && counter!==1) {
counter--;
$("#" + element.id + "l").removeClass("activa");
$(element).data(inpActive, "");
secArray2 = secArray.filter(Boolean);
inpArray[0]=$("#op" + secArray2[0]).val();
inpArray[$("#op" + secArray2[0]).data(secIndex)]="";
$("#op" + secArray2[0]).data(inpActive, "primary");
secArray[$("#op" + secArray2[0]).data(secIndex)]="";
} else
if (inpActive=="primary" && counter==1) {
counter--;
$("#" + element.id + "l").removeClass("activa");
$(element).data(inpActive, "");
inpArray[secIndex]="";
inpArray[0]=ending;
}
$(input).val(inpArray[0]+inpArray[1]+inpArray[2]);
};
This is the html code:
<input id="preco" type="text" name="preco" value='1 AND 5000'><br><br>
<input id="process" type="text" name="process" value='1 AND 11'><br><br>
<div id="op1l" class="input">
<input type="checkbox" id="op1" class="opcaopreco" value="201 AND 400" data-cpindex="1" data-cpactivo="">
<label for="op1"></label>
<span class="itext">€201 - €400</span>
</div>
<div id="op2l" class="input">
<input type="checkbox" id="op2" class="opcaopreco" value='401 AND 600' data-cpindex="2" data-cpactivo="">
<label for="op2"></label>
<span class="itext">€401 - €600</span>
</div>
<div id="op3l" class="input">
<input type="checkbox" id="op3" class="opcaopreco" value='601 AND 800' data-cpindex="3" data-cpactivo="">
<label for="op3"></label>
<span class="itext">€601 - €800</span>
</div>
<div id="op4l" class="input">
<input type="checkbox" id="op4" class="opcaopreco2" value="1 AND 1" data-cpindex8="1" data-cpactivo8="">
<label for="op4"></label>
<span class="itext">1 AND 1</span>
</div>
<div id="op5l" class="input">
<input type="checkbox" id="op5" class="opcaopreco2" value='2 AND 2' data-cpindex8="2" data-cpactivo8="">
<label for="op5"></label>
<span class="itext">2 AND 2</span>
</div>
<div id="op6l" class="input">
<input type="checkbox" id="op6" class="opcaopreco2" value='3 AND 3' data-cpindex8="3" data-cpactivo8="">
<label for="op6"></label>
<span class="itext">3 AND 3</span>
</div>
<div id="paramount">paramount</div>

You're initializing your counter to 0. It hits the if counter == 0 and wont continue to the else where you have the Test2 check

Ok let me show you much nicer solution for your problem:
https://jsfiddle.net/11jm9k7a/10/
Sorry I just couldn't work with your code so I totally reworked your logic - might be that I missed something so let me know. This solution will work on unlimited different parameter groups, as long as you put on each checkbox element 2 different attributes, first one is query before which will hold string that goes before group in your first case:
query-before="BETWEEN"
and some string to identify group of query for your first case:
query-type="opcaopreco"
there's no need for any class/id's manipulations since this is generic solution.
HTML:
<br>
<br>
<label for="process">Final Query</label>
<input id="process" type="text" name="process" value='' placeholder='1 AND 11'>
<br>
<br>
<div id="op1l" class="input">
<input type="checkbox" id="op1" query-before="BETWEEN" query-type="opcaopreco" class="opcaopreco" value="201 AND 400" data-cpindex="1" data-cpactivo="">
<label for="op1"></label>
<span class="itext">€201 - €400</span>
</div>
<div id="op2l" class="input">
<input type="checkbox" id="op2" query-before="BETWEEN" query-type="opcaopreco" class="opcaopreco" value='401 AND 600' data-cpindex="2" data-cpactivo="">
<label for="op2"></label>
<span class="itext">€401 - €600</span>
</div>
<div id="op3l" class="input">
<input type="checkbox" id="op3" query-before="BETWEEN" query-type="opcaopreco" class="opcaopreco" value='601 AND 800' data-cpindex="3" data-cpactivo="">
<label for="op3"></label>
<span class="itext">€601 - €800</span>
</div>
<div id="op4l" class="input">
<input type="checkbox" id="op4" query-before="" query-type="opcaopreco2" class="opcaopreco2" value="1 AND 1" data-cpindex8="1" data-cpactivo8="">
<label for="op4"></label>
<span class="itext">1 AND 1</span>
</div>
<div id="op5l" class="input">
<input type="checkbox" id="op5" query-before="" query-type="opcaopreco2" class="opcaopreco2" value='2 AND 2' data-cpindex8="2" data-cpactivo8="">
<label for="op5"></label>
<span class="itext">2 AND 2</span>
</div>
<div id="op6l" class="input">
<input type="checkbox" id="op6" query-before="" query-type="opcaopreco2" class="opcaopreco2" value='3 AND 3' data-cpindex8="3" data-cpactivo8="">
<label for="op6"></label>
<span class="itext">3 AND 3</span>
</div>
Javascript:
$(function() {
let query = {};
// itterate through all input elements that have query-type attribute
$('input[query-type]').each(function(value) {
query[$(this).attr('query-type')] = {
list: [],
queryBefore: $(this).attr('query-before'),
};
});
/* we first need to initialize arrays so we can get in your case:
query: {
opcaopreco: {
list: [],
queryBefore: 'BETWEEN'
},
opcaopreco2: {
list: [],
queryBefore: ''
},
}
*/
// after that attach on click even on all input elements that have query-type attribute
$('input[query-type]').on('click', function(event) {
// get query-type of $(this) - currently clicked element
let typeOfQuery = $(this).attr('query-type');
// check if this element is checked
if ($(this).is(":checked")) {
/* if it is checked, push value to object and you will get
query: {
opcaopreco: {
list: ['201 AND 400'],
queryBefore: 'BETWEEN'
},
opcaopreco2: {
list: [],
queryBefore: ''
},
}
*/
query[typeOfQuery].list.push($(this).val());
} else {
// remove - splice element from array - check index of value and remove 1 element at that index
query[typeOfQuery].list.splice(query[typeOfQuery].list.indexOf($(this).val()), 1);
}
// we also need to sort array to get remove order which people clicked
query[typeOfQuery].list.sort();
// create temporary array that will hold query
let fullQuery = [];
// loop through object keys
Object.keys(query).forEach((value, index) => {
// if there's something in array then do something otherwise don't do anything
if (query[value].list.length > 0) {
// first query join array with string ' AND ' to get ' AND ' between all values
// after that split it to get all values in correct order
let arrQuery = query[value].list.join(' AND ').split(' AND ');
// use string literal to create a string which is basically first element and last element
fullQuery.push(`${query[value].queryBefore} ${arrQuery[0]} AND ${arrQuery[arrQuery.length-1]}`);
// this is same as using + sign on each element with spaces in between like below
// fullQuery.push(query[value].queryBefore + ' '+ arrQuery[0] + ' AND '+ arrQuery[arrQuery.length-1]);
}
});
// join all query types with OR keyword
$('#process').val(fullQuery.join(' OR '));
});
});
This solution is very extendable and will work in most cases it won't cover every possible scenario and parts of it may require more work depending on your exact parameters that you need or that before part and I just join everything with 'OR', but will work very good for similar type of thing.

Related

What is an efficient way to check if an HTML input is right or wrong?

I'm creating a quiz with <input type="text"> and <input type="number">.
I find that making a bunch of if / else statements is extremely inefficient, due to the bulk of the JavaScript code.
Here is my HTML code:
<!--Question 1-->
<label for="a">A cow says =</label>
<input type="text" id="a"/>
<!--Question 2-->
<label for="a">1 + 1 =</label>
<input type="number" id="b"/>
<button onclick="checkQuiz()">Check Quiz</button>
Here is my JavaScript code:
var a = document.getElementById("a")
var b = document.getElementById("b")
function checkQuiz() {
// Question 2
if (a.value == "moo") {
console.log("correct")
}
else {
console.log("wrong")
}
// Question 2
if (b.value == "2") {
console.log("correct")
}
else {
console.log("wrong")
}
}
I'm down for some Jquery code answers, just I'm also don't know much about it.
Make an array of correct answers, and look up the index of the question input in the answer array to compare the appropriate value.
// tweak the selector as needed
// you'll probably want something more precise
const questionInputs = document.querySelectorAll('input');
const correctAnswers = ['moo', '2'];
function checkQuiz() {
questionInputs.forEach((input, i) => {
console.log(`Question ${i + 1}: ${input.value === correctAnswers[i] ? 'Correct' : 'Wrong'}`);
});
}
<!--Question 1-->
<label for="a">A cow says =</label>
<input type="text" id="a"/>
<!--Question 2-->
<label for="a">1 + 1 =</label>
<input type="number" id="b"/>
<button onclick="checkQuiz()">Check Quiz</button>

How can I prevent my program from converting selected number which starts with 0 to octal value using javascript?

When I select a number that starts with 0, such a number is converted to its octal form which I don't want but works perfectly well for those that didn't start with 0. Attached is pictures explaining what I mean.
Before Selection of Number starting with 0
After Selection of Number starting with 0
From the picture you can see 0703 got converted to 451. How can I stop this.
let phoneNumberSelector = document.querySelector("#phone");
const mtnNumber = ['703', '706', '803', '806', '810', '813', '814', '816', '903', '906', '913', '0703', '0706'];
phoneNumberSelector.addEventListener('keyup', (e) => {
removeElements();
for (let i of mtnNumber) {
// i = i.toString();
if (i.startsWith(phoneNumberSelector.value) && phoneNumberSelector.value != '') {
let listItem = document.createElement("li");
listItem.classList.add('list-items');
listItem.style.cursor = 'pointer';
listItem.setAttribute('onclick', "displayNames(" + i + ")")
let word = "<b>" + i.slice(0, phoneNumberSelector.value.length) + "</b>";
word += i.slice(phoneNumberSelector.value.length);
listItem.innerHTML = word;
document.querySelector('.list').appendChild(listItem);
}
}
})
function displayNames(param) {
phoneNumberSelector.value = param;
removeElements();
}
function removeElements() {
let items = document.querySelectorAll('.list-items')
items.forEach((element) => {
element.remove();
});
}
<section class="section1"></section>
<section class="section2">
<div class="reg-form">
<form action="" method="">
<div class="form-container">
<h1 style="text-align: center;">Phonie</h1>
<div class="input-reg email-input">
<label for="username">Username</label>
<input id="username" type="text" name="username">
</div>
<div class="list-div">
<ul class="list"></ul>
</div>
<div class="input-reg email-input">
<label for="phone">Phone Number</label>
<input id="phone" type="text" name="phone">
</div>
<div class="input-reg email-input">
<input class="submit-btn submit-btn2" type="submit" value="Check Number">
</div>
</div>
</form>
</div>
</section>
The numbers are getting converted to octal because you are passing the number (of type string) to the displayNames function as a number (without quotes).
This is the offending line:
listItem.setAttribute('onclick', "displayNames(" + i + ")")
with the value of i set to "0703", the value for onclick becomes "displayNames(0703)".
You can fix this by adding quotes around the i variable in the string passed as onclick.
For example:
listItem.setAttribute('onclick', "displayNames('" + i + "')");
or with a string template to make it a bit easier to read:
listItem.setAttribute('onclick', `displayNames("${i}")`);

Adding values to placeholder using checkbox

Basically I have 4 checkbox elements in my form and a text field up top. The text field has a placeholder with a product name — product price format. Each checkbox has a product name and product price as well, and I want to use javascript to change the placeholder value once a checkbox is checked. The issue is that the product price should be a SUM of default placeholder base price and the product price of the checkbox that was checked. The first part of the placeholder should change from product name to product name + product name.
So far I have only been able to use javascript to change the value of the placeholder entirely, which would work if I had only one checkbox, but I have 4 so it doesn't.
In a perfect world the placeholder should display Basic Package + Video + Picture + Tour + Emergency — €30 when all checkboxes are checked, and Basic Package + Picture + Tour — €20 when only Option2 and Option3 are checked. And so on, and so on.
Here is a simplified code of what I am trying to achieve (note: only Video works in my code):
$('.Option1').on('change', function(e) {
if ($(this).is(':checked') === true) {
$('.PriceInput').attr('placeholder', 'Basic Package + Video — €15');
} else $('.PriceInput').attr('placeholder', 'Basic Package — €10');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact-basic" method="post" action="mailer-basic.php">
<div class="field">
<input class="form-control PriceInput" type="text" name="basicpackage" id="basicpackage" placeholder="Basic Package — €10" disabled />
</div>
<div class="field">
<input class="Option1" type="checkbox" id="videobasic" name="optiesbasic[]" value="Video">
<label for="videobasic">Video — €5</label>
</div>
<div class="field">
<input class="Option2" type="checkbox" id="picturebasic" name="optiesbasic[]" value="Picture">
<label for="picturebasic">Picture — €5</label>
</div>
<div class="field">
<input class="Option3" type="checkbox" id="tourbasic" name="optiesbasic[]" value="Tour">
<label for="tourbasic">Tour — €5</label>
</div>
<div class="field">
<input class="Option4" type="checkbox" id="emergencybasic" name="optiesbasic[]" value="Emergency">
<label for="emergencybasic">Emergency — €5</label>
</div>
I've removed the number from each class="Option"
then you can do something like this:
$('.Option').on('change', function(e) {
var s = "";
var p = 10;
$('.Option').each(function() {
if ($(this).is(':checked') === true) {
s += " + " + $(this).val();
var tempP = +$(this).next().text().split('€')[1];
p = p + tempP;
}
});
$('.PriceInput').attr('placeholder', 'Basic Package' + s + ' — €' + p);
});
Demo
$('.Option').on('change', function(e) {
var s = "";
var p = 10;
$('.Option').each(function() {
if ($(this).is(':checked') === true) {
s += " + " + $(this).val();
var tempP = +$(this).next().text().split('€')[1];
p = p + tempP;
}
});
$('.PriceInput').attr('placeholder', 'Basic Package' + s + ' — €' + p);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact-basic" method="post" action="mailer-basic.php">
<div class="field">
<input class="form-control PriceInput" type="text" name="basicpackage" id="basicpackage" placeholder="Basic Package — €10" disabled />
</div>
<div class="field">
<input class="Option" type="checkbox" id="videobasic" name="optiesbasic[]" value="Video">
<label for="videobasic">Video — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="picturebasic" name="optiesbasic[]" value="Picture">
<label for="picturebasic">Picture — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="tourbasic" name="optiesbasic[]" value="Tour">
<label for="tourbasic">Tour — €5</label>
</div>
<div class="field">
<input class="Option" type="checkbox" id="emergencybasic" name="optiesbasic[]" value="Emergency">
<label for="emergencybasic">Emergency — €5</label>
</div>

Trying to transform words in an array and output them onto the page, using forEach method, but each entry overwrites the previous item?

I'm trying to wrap the words that are entered into the text area, by splitting them into an array, and using the foreach method to wrap each word in different keyword styles. Which all works in the console. But when I try and output it onto the DOM, it only displays the LAST item in the array, as they are overwriting the previous items... I might be going about it the wrong way, open to suggestions for re-factoring.
For example:
If you type in
'mens shoes, cheap mens shoes, affordable mens shoes'
It only displays: +affordable +mens +shoes.
I want it to display all of them in the new format.
const mainInput = document.getElementById('main-input');
const mainOutput = document.getElementById('main-output');
let keywordsArray;
mainInput.addEventListener('input', updateValue);
function updateValue(e) {
const mainInput = document.getElementById('main-input');
const mainOutput = document.getElementById('main-output');
keywordsArray = mainInput.value.split('\n');
keywordsArray.forEach(textUpdater);
function textUpdater(item, index, array) {
console.log(item)
console.log(item.replace(/(^|\s+)/g, "$1+"))
console.log('[' + item + ']');
console.log('"' + item + '"');
mainOutput.innerText = '[' + item + ']';
};
}
<div class="container">
<div class="input-box">
<textarea name="main-input" id="main-input" class="main-input" cols="30" rows="10" placeholder="Enter Keywords Here..."></textarea>
<p>What match types?</p>
<div class="type-selectors">
<p>Broad:</p> <input type="checkbox" id="broadCheck" checked onclick="updateValue()">
<p>Modified:</p> <input type="checkbox" id="modifiedCheck" checked onclick="updateValue()">
<p>Phrase:</p> <input type="checkbox" id="phraseCheck" checked onclick="updateValue()">
<p>Exact:</p> <input type="checkbox" id="exactCheck" checked onclick="updateValue()">
</div>
</div>
<div class="output-box">
<textarea class="main-output" id="main-output"></textarea>
</div>
</div>
You should use += to append text instead of overwriting the previous text. Moreover, you should set the value of the textarea instead of it's innerText.
mainOutput.innerText = '[' + item + ']';
Should be changed to:
mainOutput.value += '[' + item + ']';
const mainInput = document.getElementById('main-input');
const mainOutput = document.getElementById('main-output');
let keywordsArray;
mainInput.addEventListener('input', updateValue);
function updateValue(e) {
const mainInput = document.getElementById('main-input');
const mainOutput = document.getElementById('main-output');
keywordsArray = mainInput.value.split('\n');
keywordsArray.forEach(textUpdater);
function textUpdater(item, index, array) {
//console.log(item)
//console.log(item.replace(/(^|\s+)/g, "$1+"))
//console.log('[' + item + ']');
//console.log('"' + item + '"');
mainOutput.value += '[' + item + ']';
};
}
<div class="container">
<div class="input-box">
<textarea name="main-input" id="main-input" class="main-input" cols="30" rows="10" placeholder="Enter Keywords Here..."></textarea>
<p>What match types?</p>
<div class="type-selectors">
<p>Broad:</p> <input type="checkbox" id="broadCheck" checked onclick="updateValue()">
<p>Modified:</p> <input type="checkbox" id="modifiedCheck" checked onclick="updateValue()">
<p>Phrase:</p> <input type="checkbox" id="phraseCheck" checked onclick="updateValue()">
<p>Exact:</p> <input type="checkbox" id="exactCheck" checked onclick="updateValue()">
</div>
</div>
<div class="output-box">
<textarea class="main-output" id="main-output"></textarea>
</div>
</div>

Function that will only push value of most recent inputs

I have 3 groups of inputs, in chronological order (manufacturer info, repair info, test info). When the user hits the "confirm button", I want an if statement to iterate through each input, compare if (input.val() !== ""), and then make sure it is the most recent data (ie. repair info will supercede mfg info) before pushing that value to the #asreceived fields.
I have manually done an if statement for each set of inputs to iterate through, however I would have to add to the function if I wanted to enter more fields.
This is what I have currently:
$("#model-received").val(function() {
if ($("#model-test").val() != "") {
return $("#model-testonly").val();
} else if ($("#model-repair").val() != "") {
return $("#model-repair").val();
} else {
return $("#model-initial").val();
}
});
I have used this code for each set of inputs (roughly 50)
I have tried to compare groups using the .each(), but I am stuck here.
let $inputMfg = $("#manufacturers-tag").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-initial") > -1) {
return
}
});
let $inputRep = $("#repairtag-old").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-repair") > -1) {
return
}
});
let $inputTO = $("#testonlytag-old").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-testonly") > -1) {
return
}
});
let $inputAsRec = $("#asreceived").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-received") > -1) {
return
}
});
$("#asreceived"),$("#testonlytag-old"),$("#repairtag-old"),$("#manufacturers-tag") are all the same HTML, minus the name suffix on each input ("-initial")
HTML
<div id="repairtag-old" hidden>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Company: </label>
<input class="entry-input" type="text" name="company-repair">
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Date: </label>
<input class="entry-date" type="date" name="date-repair">
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">VR Stamp: </label>
<select class="entry-select" id="vrstamp-old" name="vrstamp-old">
<option></option>
<option>Yes</option>
<option>No</option>
</select>
<label class="entry-bylabel">VR: </label>
<input class="entry-input" type="text" name="vrnumber-old">
</div>
</div>
<div class="entry-col2">
<div class="entry-line">
<label class="entry-label">Job Number: </label>
<input class="entry-input" type="text" name="jobnumber-repair">
</div>
</div>
<div class="entry-col2">
<div class="entry-line">
<label class="entry-label">Model Number: </label>
<input class="entry-input" id="model-repair" type="text" name="model-repair">
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Set Pressure: </label>
<input class="entry-input" id="setpressure-repair" type="text" name="setpressure-repair">
<select class="entry-select" name="setunit-repair">
<option>psig</option>
</select>
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Cold Test Pressure: </label>
<input class="entry-input" type="text" name="coldpressure-repair">
<select class="entry-select" name="coldunit-repair">
<option>psig</option>
</select>
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Capacity: </label>
<input class="entry-input" type="text" name="capacity-repair">
<select class="entry-select" name="capacityunit-repair">
<option>scfm</option>
</select>
</div>
</div>
<br>
</div>
The final result should push the value of the most important value (test only 1st, repair 2nd, mfg 3rd). If the (input.val === ""), it should use the older values.
---UPDATED---
I figured it out. Code snippet below. Thank you for the responses, I was a little intimated in trying to implement them (I am new at coding). However, Mark Meyer's response got me on the right track. This works exactly as intended.
$("#copybtn-received").click(function(i) {
$("#asreceived").find("input, select").each(function() {
let $output = $(this).attr("name").split("-received")[0];
let $inputTO = $("#testonlytag-old").find("[name^=" + $output + "]");
let $inputRep = $("#repairtag-old").find("[name^=" + $output + "]");
let $inputMfg = $("#manufacturers-tag").find("[name^=" + $output + "]");
if ($inputTO.val() !== "") {
$(this).val($inputTO.val());
} else if ($inputRep.val() !== "") {
$(this).val($inputRep.val());
} else if ($inputMfg.val() !== "") {
$(this).val($inputMfg.val());
} else {
$(this).val("");
}
});
});
You could put your values in an array that is in the order of precedence you want then use find() which returns the first value found. In the find callback just return whether the value is truth, which "" isn't. This will allow you to decide arbitrary orders without all the if/else statements.
Here's a simplified example. It will log the highest value filled in.
function getBest(){
/* values in the order values will be found */
let values = [
document.getElementById("one").value,
document.getElementById("two").value,
document.getElementById("three").value,
document.getElementById("four").value
]
/* find the first truthy value */
let best = values.find(val => val)
console.log(best)
}
<input id="one" type ="text"><br />
<input id="two" type ="text"><br />
<input id="three" type ="text"><br />
<input id="four" type ="text"><br />
<button onclick="getBest()">Go</button>
I'm not sure I understand the question correctly, so this is a bit of a guess. Perhaps something like this would do?:
const findFirst = (ids, idx = ids.find(id => $(`#${id}`).val() !== '')) =>
idx > -1 ? $(`#${id}`).val() : 'not found'
$("#model-received").val(findFirst(
['model-testonly', 'model-repair', 'model-initial']
))
You can then update the list by simply appending to that array. And if the 'model-' prefix is universal, you can include that in the function and only pass ['testonly', 'repair', 'initial'] in the call.
I don't know if you have a better default than the 'not found' here.

Categories

Resources