开发者

jQuery: split string and then insert into input and select

I have strings like this:

"Car is blue"

String could also be like this:

"Flower is not at all beautiful"

I have html like this:

<input class="subject" />
<select class="isornot">
    <option>is</option>
    <option>is not<开发者_JAVA百科;/option>
</select>
<input class="adjective" />

I need to split the string and put it into the appropriate places in the form. For the first string, the subject val should be car, is should be selected, and adjective value should be blue. For the second string, flower is the subject, is not is the select option, and 'at all beautiful' should be the adjective.

Therefore the split should be is or is not. Not sure how to go about it. Thanks.


Here you go:

var str = "Car is not blue";
var match = str.match(/^(.+?)\s+(is(?:\snot)?)\s+(.+)$/);
if (match) {
    $('input.subject').val(match[1]);
    $('select.isornot').val(match[2]);
    $('input.adjective').val(match[3]);
} else {
    alert("Could not parse message.");
}

References:

  • Using Regular Expressions with JavaScript
  • Re: [jQuery] Set selected option


Adding a input box with the ID "string"


function split()
{
 var strings=$("#string").attr("value").split("is not");
 if (strings.length==2){
    assingData(strings,1);  
 }
 else{
    strings=$("#string").attr("value").split(" is ");
    assingData(strings,0);
 }
}

function assingData(value,index){
    if(value.length==2){
        $(".subject").attr("value",value[0]);       
        $(".isornot option:eq("+index+")").attr("selected", "selected");
        $(".adjective").attr("value",value[1]);
    }
    else{
        alert("malformed strings");
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜