简体   繁体   中英

Javascript repeating if statements better solution?

I have 3 inputs and the code checks if they are empty and if they are then the variable values are added to the inputs.

So I have 3 variables with values:

var input1text = "something here";
var input2text = "something else here";
var input3text = "something else 2 here";

So when the page loads, I check if the inputs are empty and if they are I add the variable values to the inputs.

Like this:

if($('#input1').val() == '') {

    //Add input1text text to it

}

if($('#input2').val() == '') {

    //Add input2text text to it

}


if($('#input3').val() == '') {

    //Add input3text text to it

}

My question is, it having multiple if s the most elegant way to do this? Is there a better way?

You could create an object with keys the ids of your html elements and values their default values:

var inputDefaultValues = {
    "input1": "something here",
    "input2": "something else here",
    "input3":  "something else 2 here"
};

Then you could loop through the keys of this object, check if the value of the corresponding element is empty and if it is empty to aplly the default value:

Object.keys(inputDefaultValues)
      .forEach(function(key){
          var inputElement = document.getElementById(key);
          if(inputElement.value === ''){
              inputElement.value = inputDefaultValues[key];
          }
      });

 var inputDefaultValues = { "input1": "something here", "input2": "something else here", "input3": "something else 2 here" }; Object.keys(inputDefaultValues) .forEach(function(key){ var inputElement = document.getElementById(key); if(inputElement.value === ''){ inputElement.value = inputDefaultValues[key]; } }); 
 <input type="text" id="input1"/> <input type="text" id="input2"/> <input type="text" id="input3"/> 

How about this - the order doesn't matter, super flexible and super compact.

var defaults = {
   "#input1": "something here",
   "#input2": "...",
   "#input3": "..."
};

for (var id in defaults) {
   var currVal = $(id).val();
   $(id).val(currVal.trim() || defaults[id]);
}

We can extract an abstraction over the operation of checking the fields and putting the default value.

var fields = [{
    selector: "#input1",
    defaultVal: "default1"
}, {
    selector: "#input2",
    defaultVal: "default2"
}, {
    selector: "#input3",
    defaultVal: "default3"
}
];

var setDefault = function (selector, default) {
    if($(selector).val() == '') {
        $(selector).val(default);
    }
}

for (var i = 1; i < fields.length; i++) {
    var field = fields[i];
    setDefault(field.selector, field.defaultVal);
}

You could use .each() to check every input and if it's empty - assign corresponding value from an array holding the values.

 var inputs = ['something here', 'something else here', 'something else 2 here']; $('input').each(function(i){ $(this).val() == '' ? $(this).val(inputs[i]) : null; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='input1' value='x'> <input id='input2'> <input id='input3'> 

 var inputs = {input1:'something here', input2:'something else here', input3: 'something else 2 here'}; $('input').each(function(i){ $(this).val() == '' ? $(this).val(inputs[$(this).attr('id')]) : null; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='input1' value='x'> <input id='input2'> <input id='input3'> 

Try with simple forEach and querySelector() for pure javascript

 var input1text = 'something here'; var input2text = 'something else here'; var input3text = 'something else 2 here'; document.querySelectorAll('input').forEach(function(a,b){ a.value = a.value ? a.value :window['input'+(b+1)+'text'] ; }) 
 <input id="1" value="dddddddd"><input id="2"><input id="3"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM