0

I have a numeric sequence from 0 to 99:

0 1 2 3 4 5 . . . 99

In this case, i'm trying to put some numbers in bold after clicking a button. For example, within a first input there is the number 2 and within a second input there is the number 99, and after clicking on a button, the number 2 and 99 are in bold as below:

0 1 2 3 4 5 . . . 99

I tried to find some similar questions, but unfortunatly i didn't find some solution to improve my script yet:

  1. Jquery how to check if a input has a number higher then 99

  2. I Want To Print 1 to 100 Numbers Using Arrays In Javascript Only

  3. How to format numbers by prepending 0 to single-digit numbers?

At first i'm trying with the following HTML code and a jquery script to apply this solution, but i'm not able to improve it to get the final result:

HTML code:


<input type="number" id="field1" value="2"/>
<br>
<input type="number" id="field2" value="99"/>
<br>
<button type="button" id="getBtn">show me the highlighted numbers</button>
<br>

<div id="sequence"></div>

Jquery script to call click event:

$('#getBtn').on( "click", function() {

  var field1 = $('#field1').val();
  var field2 = $('#field2').val();

// From this point, i don't know how to improve the script to display a sequence number with the highlighted numbers.

for(let i = 0;i <= 100;i++){

    console.log(i);

}

$("#sequence").html();


});


How can i improve my script to find a viable solution?

2
  • Why do you use a console.log? You should append the number into a div tag's innerText wrapping up your number inside the bold tag. E.g: "<b>" + i +"</b>" Commented Nov 28, 2023 at 3:04
  • Actually, I just left it as a way to consult the result through the console. Commented Nov 28, 2023 at 11:05

1 Answer 1

2

You could create an array of strings (wrapping the number in a <strong> element when it's one of the inputs) and then join on space at the end to create the HTML.

$('#getBtn').click(function(e) {
  const vals = $('input[type=number][id^=field]').map((i, el) => el.valueAsNumber).get();
  const seq = [];
  for (let i = 0; i < 100; i++)
    seq.push(vals.includes(i) ? `<strong>${i}</strong>` : i);
  $("#sequence").html(seq.join(' '));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="field1" value="2" />
<br>
<input type="number" id="field2" value="99" />
<br>
<button type="button" id="getBtn">show me the highlighted numbers</button>
<br>
<div id="sequence"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I will improve the script with this solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.