Home > Mobile >  How I get Input text string value to javascript?
How I get Input text string value to javascript?

Time:09-29

I'm still learning Javascript and I need to get input type text value to javascript code and convert it to integer. but everytime it display "Your fail" even i input higher mark. I need help to find my error.

function mark() {
    var sMark = document.form.mark.value;
    var myMark = parseInt(sMark);
    if (myMark > 75) {
        document.write("You  pass exam with Higher mark");

    } else if (myMark > 50) {
        document.write("You pass exam");

    } else {
        document.write("You Fail");
    }
}
<form action="" name="form">
        Enter Your Mark: <input type="text" name="mark" id="mark1">
        <input type="submit" value="Submit" onclick="mark()"><br>
    </form>


CodePudding user response:

The input with the name "mark" is shadowing the global mark function in the inline onclick handler. Either rename those or directly call window.mark().

function mark() {
  var sMark = document.form.mark.value;
  var myMark = parseInt(sMark);
  if (myMark > 75) {
    document.write("You  pass exam with Higher mark");

  } else if (myMark > 50) {
    document.write("You pass exam");

  } else {
    document.write("You Fail");
  }
}
<form action="" name="form">
  Enter Your Mark: <input type="text" name="mark" id="mark1">
  <input type="submit" value="Submit" onclick="window.mark()"><br>
</form>

CodePudding user response:

There are some issues with your code.

  1. Use the <label> element to display text that is related to an input element.
  2. Don't use document.write(), just don't.
  3. Use type="number" for an <input> element if you'd like to just receive numbers.
  4. Using onclick is bad practice. Register event listeners using addEventListener() instead.

const result = document.querySelector('#result');
const form = document.forms['mark-form'];

function handleSubmit(e) {
    e.preventDefault();

    const { mark } = e.currentTarget.elements;
    const value = mark.valueAsNumber;

    switch (true) {
        case value > 75:
            result.textContent = 'You pass with a higher mark.';
            break;
        case value > 50:
            result.textContent = 'You pass the exam.';
            break;
        default:
            result.textContent = 'You fail.';
    }
}

form.addEventListener('submit', handleSubmit);
<h1 id="result"></h1>
<form name="mark-form">
    <label for="mark-input">Enter your mark:</label>
    <input type="number" name="mark" id="mark-input" />
    <button type="submit">Submit</button>
</form>

  • Related