MattSizzle
MattSizzle

Reputation: 3175

Switch Statements in Javascript based on input text value

I am trying to accomplish the following currently and am not very familiar with Javascript so I am hoping I could get some good suggestions and answers for the following as I have gotten such great help with my Javescript questions here before.

Basically I have an input field where the user will enter a value. Once that value is entered I want to provide the user some information in a div, prior to them submitting the value to the Ajax handler. I would also like to have the values presented to them on each change of the input fields text. I have 3 different types of data being submitted so for each type I would like to present different information sets to the user based on what their input contains. For this I use a switch, but the switch is currently not working as it appears below.

function createLinks() {
    var sv = document.getElementById('sv').value // Input Text
    var div = document.getElementById('svResult');

    switch (true) {
    case (sv.indexOf('1') >= 0):
        div.innerHTML="1 Links: ";
        break;
    case (sv.indexOf('2') >= 0):
        div.innerHTML="2 Links: ";
        break;
    case (sv.indexOf('3') >= 0):
        div.innerHTML="3 Links: ";
        break;
    }
//div.innerHTML=sv.value;
}

<div>
    <form>
        <label for="sv">Server:</label>
        <input type="text" id="sv" size="16" title="Coming Soon" onchange="createLinks()"/>
        <input type="submit" style="margin-left: 10px;" value="Search" class="button1"/>
    </form>
    <div id="svResult"></div>
</div>

When I just display the sv.value in the div assigned to the div variable it displays correctly, but when the switch is introduced I do not get any output. The switch is based on the return of each case statement being either true or false, but there is probably something simple I am missing.

I did see this which helped get the input value into the variable correctly, but focuses more on if statements.

Upvotes: 1

Views: 2881

Answers (1)

RobG
RobG

Reputation: 147373

In the HTML, there is no need for an ID attribute and form controls must have a name to be successful. You can also pass a reference to the element from the listener:

<input type="text" name="sv" size="16" title="Coming Soon" onchange="createLinks(this)">

Then the script can be something like:

function createLinks(el) {
  var value = el.value;
  var div = document.getElementById('svResult');

  if (value.indexOf('1') != -1) {
    div.innerHTML = '1 Link';

  } else if (value.indexOf('2') != -1) {
    div.innerHTML = '2 Links';

  } else if (value.indexOf('3') != -1) {
    div.innerHTML = '3 Links';
  }

  } else {
    div.innerHTML = '';
  }
}

The above will return on the first match, so an input of '123' will report "1 link". Also, the change event is dispatched when the control loses focus, which might be later than you want.

Upvotes: 1

Related Questions