0

I'm currently trying to find a way to fill the max value of an input according to the

max="@value"

Currently I'm using asp.net mvc, I'm getting data from a datatable and I render this information inside a html table where in my tr> /tr> I have a td> /td> that looks like this

 <td align="center"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" min="0" max="@monto.Trim()" value="" step="any" style="width: 100px" /></td>1

Can anyone tell me how to make a javascript function that automatically fills the max="" value inside a Html TableRow?

The problem is that each row has its unique max @value

6
  • In what context? If you have an element reference then you can get the attribute value by element.max if it's in an event handler then you could probably use event.currentTarget.max and so on Commented Nov 28, 2019 at 22:28
  • Replace oninput="setValueAttr(this)" with onclick="this.value=max". Commented Nov 28, 2019 at 22:28
  • I'm currently using oninput="setValueAttr(this)" on another script where I push into an array the rows that do have a value in the input in order to post it with AJAX function setValueAttr(el) {el.setAttribute('value', el.value)} Commented Nov 28, 2019 at 22:31
  • @apokryfos can you give me an example with an event handler? I'm currently looking for a way to do it this way, will adding a button on the same <td> catch the event handler? Commented Nov 28, 2019 at 22:33
  • 1
    Well I do not know what the idea behind you code actually is, but onclick is not the same as oninput. So if you want to react on click, like the title suggests, use onclick. Commented Nov 28, 2019 at 22:33

1 Answer 1

1

Assume the following HTML:

<td align="center">
     <input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" min="0" max="@monto.Trim()" value="" step="any" style="width: 100px" />
     <button class="set-max">Max value</button>
</td>

You can add an event listener on the button via JavaScript e.g. put this code in the bottom of your table or in the bottom of the <body> tag.

<script>
var buttons = document.querySelectorAll('.set-max'); 
buttons.forEach(function (button) {
   button.addEventListener('click', function (event) {
       var input = event.currentTarget.parentElement.querySelector('input[type="number"]');
       input.value = input.max;
   });
};
<script>

If the button ends up somewhere else you'd need to adjust the event listener to find the actual target element by navigating through the DOM hierarchy

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

1 Comment

Yay thanks for the explanation, totally helped me out thanks sir!

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.