How to handle (String) value with jquery?

Asked

Viewed 246 times

2

I have a field that when it is filled it makes several triggers, beauty so far, everything well achieved with the code below.

$("#teste").change(function () {
    var valor = $(this).val();
    $("#nome").val(valor);
    $("#idade").val(valor);
});

The problem is that my field comes with an example information, maicon/29, name and age as I do in jQuery to get all the information up to the bar and also get all the information after the bar, as I do this? And if I have another bar, how to treat it?

  • 1

    post your html so we can see

  • 1

    Will the information always be name/age? Or can you have more information? name/age/city/state? You can try using a split valor.split('/'), will return an array with all the information. Post your HTML to get a better idea of how to respond.

  • 1

    @cbonimini , I guess you didn’t read the question right. (with do this and if I have another bar how to treat it.)

  • 1

    @If Maicon has more than one bar, how should it look? "banana/potato/35" should be "banana/potato" the name, and 35 age? I put a bold at the end of your question, so you don’t forget that point in the answer, but it would be good if you [Edit] and add input examples with extra bars, and how you want the output in these cases.

1 answer

6


Try to use the split("/"):

$("#teste").change(function () {
    var valor = this.value.split("/");
    $("#nome").val(valor[0]);
    $("#idade").val(valor[1]);
});
  • Testing with "master/Divider/37" did not work (based on the part of the question "And if I have another bar, how to treat it?").

  • Get index Last /. and loop the string for each new /.

  • To each new bar just add +1 to the number between keys[]. For example: value = split("master/Divider/37", "/"), value[0] = master, value[1] = Divider, value[2] = 37, and so on. But use this way only for a few dice, if it’s many, use a for loop.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.