Check if TextArea/TextBox contains a certain String

前端 未结 3 681
无人共我
无人共我 2020-12-20 08:52

Given textarea is a textarea element with id \'textareabox\', how can I check if it contains a string within it?

var textarea = document.getElementById(\'tex         


        
相关标签:
3条回答
  • 2020-12-20 09:30

    You can use .value, as:

    var textarea = document.getElementById('textareabox');
    
    var word = 'something';
    
    var textValue=textarea.value;  //-> don't use .innerHTML since there is no HTML in a textarea element
    
    if (textValue.indexOf(word)!=-1)
    {
      alert('found')
    }
    
    0 讨论(0)
  • 2020-12-20 09:49

    You could do something like this:

    var textarea = document.getElementById('textareabox').value;
    
    if (texarea.match(word) != null) {
        // do some stuff
    }
    

    A better regex than what I did but I don't know regex all that well (forgive me regex ignorance).

    0 讨论(0)
  • 2020-12-20 09:54

    body {
    background-color: red;
    
    
    }
    <html>
    <h1>#mywebsite</h1>
    <body>1+1=2?(yes <strong>or</strong> no)</body>
    <input type="text" id="text" placeholder="text here"></input>
    <button type="button" id="u" onclick="run()">submit</button>
    <script type="text/javascript">
    
    
    var a = 1;
    function run() {
    if (document.getElementById("text").value.includes("yes")) {
    alert("correct!");
    /*if the textbox includes "yes" it will say you got it right; basically whatever the input your user puts into the textbox it will test if the users sentence contains "yes" it alerts "correct!" into html if its wrong well it alerts "Try again!" the thing is, no matter what, if yes is in the sentance it will still say its correct.*/
    /*if the snippet will not work use a different website to put code on */
    document.body.innerHTML += "<li>attempt #" + a + ": correct";
    a++
    }
     
    else {
    
    alert("try again!")
    document.body.innerHTML += "<li>attempt #" + a + ": try again";
    a++
    }
    
    
    
    }
    </script>

    0 讨论(0)
提交回复
热议问题