Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to input variable in a text field?

I have this if condition where if you’re input "[first_name]" in the text field the result will be "John". But if you’re input "Hello [first_name]" the result will be "Hello [first_name]".

Here’s the code, i know if you’re input only "[first_name]" in text field it works. But how do i fix this if i write whatever in the text field the result would be what i write and the variable "[first_name]" would be "John". Thank you.

<p> Input [first_name] for variable </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<p id="result"></p>

function myFunction(){
    var input = document.getElementById("myInput").value;
    var myVar = "[first_name]"
    
    if (input == myVar){
        var data = document.getElementById('result').value= "John"
        document.getElementById("result").innerHTML = data;
    }
    else{
        document.getElementById("result").innerHTML = input
    }
}

What Did I Tried
Input field:
Hello [first_name]
Result:
Hello [first_name]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I’m Expecting
Input field:
Hello [first_name]
Result:
Hello John

or whatever i write in the text field with variable "[first_name]" would be "John" and another text that i write.

>Solution :

You need to modify your JavaScript code slightly. Instead of comparing the entire input string with "[first_name]", you should check if "[first_name]" is present in the input string using the indexOf() method. Here’s the modified code:

function myFunction(){
    var input = document.getElementById("myInput").value;
    var myVar = "[first_name]";
    
    if (input.indexOf(myVar) !== -1){
        var data = input.replace(myVar, "John");
        document.getElementById("result").innerHTML = data;
    }
    else{
        document.getElementById("result").innerHTML = input;
    }
}
<p>Input [first_name] for variable</p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<p id="result"></p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading