Я создал автономное приложение для Android на основе JavaScript с помощью Phonegap. В index.html есть четыре формы для поиска в базе данных:
<form onsubmit = "s1(); return false;">
<input id = "search1" type = "text" maxlength = "255" placeholder = "Search in Titles only" value = "" />
<input type = "submit" value = "Go" />
</form>
<form onsubmit = "s2(); return false;">
<input id = "search2" type = "text" maxlength = "255" placeholder = "Search in Titles + Contents" value = "" />
<input type = "submit" value = "Go" />
</form>
<form onsubmit = "scat(); return false;">
<input id = "cat" type = "text" maxlength = "255" placeholder = "Search in Categories" value = "" />
<input type = "submit" value = "Go" />
</form>
<form onsubmit = "gotoid(); return false;">
<input id = "articleid" type = "text" maxlength = "255" placeholder = "Find based on ID" value = "" />
<input type = "submit" value = "Go" />
</form>
А вот скрипт на странице:
function s1() {
window.location.href = "search1.html?" + document.getElementById("search1").value.trim().replace(/\s+/g, "+");
}
function s2() {
window.location.href = "search2.html?" + document.getElementById("search2").value.trim().replace(/\s+/g, "+");
}
function scat() {
window.location.href = "cat.html?" + document.getElementById("cat").value.trim().replace(/\s+/g, "+");
}
function gotoid() {
window.location.href = "id.html#" + document.getElementById("articleid").value.trim().replace(/\s+/g, "");
}
Проблема в том, что страница довольно грязная. Я попытался объединить эти четыре формы в одну, сохранив их функции, добавив <select> и <options>, но у меня не получалось заставить его работать.
Приветствуются любые предложения, будь то CSS, HTML, JavaScript или их комбинации (но не jQuery).



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Сделай это:
var btns = document.querySelectorAll( 'input[type = "button"]' );
btns.forEach( function( item, index) {
item.addEventListener( 'click', function() {
var elm = item.previousElementSibling,
eid = ( index !=3 ) ? elm.id + '.html?' : 'id.html#',
val = elm.value.trim().replace( /\s+/g, '+' );
/* window.location.href = eid + '.html?' + val */
console.info( eid + val )
} )
} )<form>
<input id = "search1" type = "text" maxlength = "255" placeholder = "Search in Titles only" value = "" />
<input type = "button" value = "Go" /><br />
<input id = "search2" type = "text" maxlength = "255" placeholder = "Search in Titles + Contents" value = "" />
<input type = "button" value = "Go" /><br />
<input id = "cat" type = "text" maxlength = "255" placeholder = "Search in Categories" value = "" />
<input type = "button" value = "Go" /><br />
<input id = "articleid" type = "text" maxlength = "255" placeholder = "Find based on ID" value = "" />
<input type = "button" value = "Go" /><br />
</form>О вашем обновленном коде:
Это решение лучше. Но вы можете просто сделать это, как показано ниже:
function search() {
var select = document.getElementById( 'select' ),
value = document.getElementById( 'key' ).value.trim().replace( /\s+/g,'+' );
/*window.location.href = select.options[ select.selectedIndex ].value + value;*/
console.info( select.options[ select.selectedIndex ].value + value )
}<form onsubmit = "search(); return false;">
<input id = "key" type = "text" maxlength = "255" placeholder = "" value = "" />
<select id = "select">
<option value = "search1.html?" selected>Only in Titles</option>
<option value = "search2.html?">In Titles + Contents</option>
<option value = "cat.html?">In Categories</option>
<option value = "id.html#">Based on ID</option>
</select>
<input type = "submit" value = "Go" />
</form>Ваш HTML лучше исходного HTML, но это может сбивать с толку, учитывая четыре ввода и четыре кнопки. Во всяком случае, я голосовал за это.
@Siamak, ты прав. Но я только обновил ее код. Спасибо за ваш голос.
Кавиан, обновленный код в порядке. Чем короче, тем лучше. Спасибо.
Мне удалось заставить его работать. Вот новый HTML:
<form onsubmit = "search(); return false;">
<input id = "key" type = "text" maxlength = "255" placeholder = "" value = "" />
<select>
<option id = "s1" selected>Only in Titles</option>
<option id = "s2">In Titles + Contents</option>
<option id = "scat">In Categories</option>
<option id = "gotoid">Based on ID</option>
</select>
<input type = "submit" value = "Go" />
</form>
И новый сценарий выглядит следующим образом:
function search(){
if (document.getElementById("s1").selected == true){
window.location.href = "search1.html?" + document.getElementById("key").value.trim().replace(/\s+/g,"+");
}
else if (document.getElementById("s2").selected == true){
window.location.href = "search2.html?" + document.getElementById("key").value.trim().replace(/\s+/g,"+");
}
else if (document.getElementById("scat").selected == true){
window.location.href = "cat.html?" + document.getElementById("key").value.trim().replace(/\s+/g,"+");
}
else if (document.getElementById("gotoid").selected == true){
window.location.href = "id.html#" + document.getElementById("key").value.trim().replace(/\s+/g,"");
}
else{
alert('Something went wrong. Please try again!');
}
}
Прокомментируйте, если это не стандартный способ.
Мне только что удалось заставить его работать. Пожалуйста, посмотрите и дайте мне знать, стандартный ли это способ. Спасибо