简体   繁体   中英

How do I take the value of an input field and make sure that it matches the value of a list item?

I have a list of values:

<ul>
   <li>Value1</li>
   <li>Value2</li>
   <li>Value3</li>
</ul>

I then have a series of input fields

<form>
    <input type="text" class="textinput" />
    <input type="text" class="textinput" />
    <input type="text" class="textinput" />
</form>

When it's fully styled it would then be laid out like:

list item    input field
list item    input field
list item    input field

What I would like to do is create a memorization exercise where the user inputs the text as shown in the list item into the corresponding input field next to it. Using JavaScript I then want to validate that the value typed into each input correctly corresponds to the list item. Once the entire exercise is complete then it would allow you to move on to the next exercise.

var ip = document.getElementsByTagName('form')[0];
var lis = document.getElementsByTagName('ul')[0];
for (var i = 0, len = ip.children.length; i < len; i++) {

    (function (index) {
        ip.children[i].onblur = function () {
            var lisText = lis.children[index].innerHTML;
            if (this.value == lisText) {
                alert("Valid");
            } else {
                alert("Not Valid");
            }
        }
    })(i);

}

JSFiddle

Use list item as id of textbox.

<ul>
<li>item1<input type="text" id="item1"></li>
</ul>

Now using java script get value of thw textbox.

Var textbox1=document.getElementById(item1);
Var textboxval1=textbox1.value;

Google the java script code.may be mine is wrong.but u can follow this logic.I hope it will work.

you can try this, but keep in mind that the total number of list and text boxes must be equal

<ul id="matcher">
   <li>Value1</li>
   <li>Value2</li>
   <li>Value3</li>
</ul>
<form>
    <input type="text" class="textinput" id="inpuText0"/>
    <input type="text" class="textinput" id="inpuText1"/>
    <input type="text" class="textinput" id="inpuText2"/>
</form>

JavaScript

function validate()
{
  var ul = document.getElementById('matcher');
  var ele = ul.getElementsByTagName('li');
  for( var i=0;i<ele.length;i++)
  {
    var text = ele[i].textContent || ele[i].innerText;
    if(text != document.getElementById('inputText'+i).value)
    {
        alert('value not matching for '+i+' row');
        ele[i].focus();
        return false;
    }
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM