PDA

View Full Version : Help me with this function



d9esco
02-01-2016, 01:41 AM
I have a variable that stores the value of a search box. This value is supposed to represent the id of another element. I want to use the focus command in javascript to focust on the value as an id in the page. how do I do this? This is what I had.


function search(){
var val = document.getElementById('search').value;
val.focus();
}





<body id="body" onload="document.getElementById('title').focus();">



<input value=" Search" id="search" onclick="document.getElementById('search').value=' '"></input>

<button id="button" onclick="search();">Search</button>

Beverleyh
02-01-2016, 12:14 PM
Trim extra whitespace first, and then getElementById


function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}

function search(){
var val = document.getElementById('search').value;
val = trim(val);
document.getElementById(val).focus();
}

Demo: http://jsbin.com/gunacacisa/1/edit?html,js,output