riyadi riyadi - 3 months ago 5
Ajax Question

Need more simple JS code with only one ID attribute

Example below using some name id = btnHour1, btnHour2 etc .. that made me be lengthy code.
I've been looking for a tutorial like this but it was not found.

HTML:

<div id="lblHour"></div>
<div>
<button id="btnHour1" value="03:00 PM">Available 1</button>
<button id="btnHour2" value="03:30 PM">Available 2</button>
<button id="btnHour3" value="04:00 PM">Available 3</button>
<button id="btnHour4" value="04:30 PM">Available 4</button>
<button id="btnHour5" value="05:00 PM">Available 5</button>




JavaScript:

$(document).ready(function(){
$("#btnHour1").click(function(){
var getValue = $("#btnHour1").val();
document.getElementById("lblHour").innerHTML = getValue;
});
$("#btnHour2").click(function(){
var getValue = $("#btnHour2").val();
document.getElementById("lblHour").innerHTML = getValue;
});
$("#btnHour3").click(function(){
var getValue = $("#btnHour3").val();
document.getElementById("lblHour").innerHTML = getValue;
});
$("#btnHour4").click(function(){
var getValue = $("#btnHour4").val();
document.getElementById("lblHour").innerHTML = getValue;
});
$("#btnHour5").click(function(){
var getValue = $("#btnHour5").val();
document.getElementById("lblHour").innerHTML = getValue;
});


});

I need advice to make my JavaScript code more simple and short by using only one name id = "btnHour".

Execute code:
https://jsfiddle.net/L5m8xop4/

Answer

You could use the Starts with selector (^=):

$("button[id^='btnHour'").on("click", function() {
    var getValue = $(this).val();
    document.getElementById("lblHour").innerHTML = getValue;
});

Full example:

$("button[id^='btnHour'").on("click", function() {
    var getValue = $(this).val();
    document.getElementById("lblHour").innerHTML = getValue;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="lblHour"></div>
<div>
<button id="btnHour1" value="03:00 PM">Available 1</button>
<button id="btnHour2" value="03:30 PM">Available 2</button>
<button id="btnHour3" value="04:00 PM">Available 3</button>
<button id="btnHour4" value="04:30 PM">Available 4</button>
<button id="btnHour5" value="05:00 PM">Available 5</button>