简体   繁体   中英

How can I select JavaScript “Id” by var?

All I want is set getElementById by var (it must be automatic because I have got multiple of this range inputs (brightness, contrast, sharpen, etc.). How can I do this?

  function showVal(value, id) { var spanId = "#" + id + "Id"; document.getElementById("\\"" + spanId + "\\"").innerHTML = value; } 
 <div class="row" style="display: inline-block; width: 45%; margin: 0px 5px 5px 5px;"> <div class="col-sm-5" style="padding: 2px;"> <label class="control-label" style="float: left">Jasność:</label> <span class="filterValue" id="brightnessId">0</span> </div> <div class="col-sm-7" style="padding: 2px;"> <input id="brightness" type="range" min="-100" max="100" step="1" value="0" data-filter="brightness" onchange="showVal(this.value, this.id)"> </div> </div> 

You don't need to use # , and don't need to enclose it between ""

   function showVal(value, id) {
        var spanId = id + "Id";
        document.getElementById(spanId).innerHTML = value;
   }

Here is a working example

You also could write this code like this:

function showVal(obj) {
        var spanId = obj.id + "Id";
        document.getElementById(spanId).innerHTML = obj.value;
}

and use only this in your HTML

<input id="brightness" type="range" min="-100" max="100" step="1" value="0" data-filter="brightness" onchange="showVal(this)">

Looks like you are mixing up jQuery and vanilla JavaScript . . . you should simply be able to use this:

function showVal(value, id) {
    document.getElementById(id + "Id").innerHTML = value;
}

Since you have included jQuery in tags, I'd use it. I'd also use mousemove instead of change , so that your output element gets updated at real time:

input field:

<input id="brightness" type="range" min="-100" max="100" step="1" value="0" data-filter="brightness">

jQuery:

$('#brightness').mousemove(function(){
   $('#'+$(this).attr('id')+'Id').text($(this).val());
});

DEMO


OR , Because your input field have data-filter="..." attribute and you want to have more fields which practically perform the same function (contrast, sharpness, etc...), I'd remove id , add class as selector and then use this data-filter attribute to match output element ( span ). So that is the whole process simple and automated:

<input class="settings" type="range" min="-100" max="100" step="1" value="0" data-filter="#brightness">
<input class="settings" type="range" min="-100" max="100" step="1" value="0" data-filter="#contrast">
<input class="settings" type="range" min="-100" max="100" step="1" value="0" data-filter="#sharpness">

jQuery (for all these fields):

$('.settings').mousemove(function(){
   $($(this).data('filter')).text($(this).val());
});

DEMO

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