0

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>


0

2 Answers 2

2

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>

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

1 Comment

For <input type="number">, just use mark.valueAsNumber.
2

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>

Comments

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.