我想在我的搜索表单中阻止空字段

时间:2013-11-26 00:06:11

标签: javascript forms

我绝对是javascript的初学者,如果2个字段中的2个或1个为空并且出现例如“不允许空字段”的消息,我尝试使我的(2个字段的内容和位置)搜索表单不被提交

我的2个字段是:

<input id="cf28" class="fxsearch_a1" type="text" size="30" name="cf28" />
<input id="city3" class="fxsearch_b1" type="text" size="30" name="city" />

Thanx&amp;等待你的帮助...

这是我的所有代码..

<p>
<script type="text/javascript">
// <![CDATA[
function showlayer(layer) {
var mymenu = document.getElementById(layer).style.display;
if (mymenu == "block") {
document.getElementById(layer).style.display = "none";
} else {
document.getElementById(layer).style.display = "block";
}
}
// ]]>

</script>
</p>
<p>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js
sensor=false&amp;libraries=places"></script>
<script type="text/javascript">
// <![CDATA[
function initialize() {
var input = document.getElementById('city3');
var options = {
types: ['(cities)'],
componentRestrictions: {
country: "gr"
}
};
// var options = {
//  types: ['(regions)']
// };
new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
// ]]>

</script>
</p>
<div class="fixedsearch">
<form id="Simplesearchform" action="index.php" method="post" name="Simplesearchform">  <select id="searchcondition" class="inputbox" style="display: none;" name="searchcondition" size="1"><option value="1">option 1</option><option selected="selected" value="2">option 2</option></select>
<div class="fxbrowse">
<p id="showorHide" class="browsing"><a onclick="javascript:showlayer('mymenu')">My Menu</a>
</p>
</div>
<div class="fxgroupfields">
<div class="what">What?</div><input id="cf28" class="fxsearch_a1" type="text" size="30" name="cf28" />
<div class="where">Where?</div><input id="city3" class="fxsearch_b1" type="text" size="30" name="city" /><input id="submit" class="fxbutton" type="submit" value="GO" />
</div><input type="hidden" value="103" name="Itemid" /><input type="hidden" value="com_mtree" name="option" /><input type="hidden" value="advsearch2" name="task" />
</form>
</div>
<div id="mymenu" class="menubrowse">
<div class="menulinks"><a href="catalog" target="_self">My Catalog</a>
</div>
<div class="menulinks"><a href="catalog/add" target="_self">Add New</a>
</div>

</div>

1 个答案:

答案 0 :(得分:1)

虽然这个问题标记为Java,但我认为你的意思是Javascript。

对于vanilla Javascript,你可以这样做:

// Generic validation function to ensure you Don't Repeat Yourself (DRY)
function validate(obj) {
    if (!obj.value) {
        document.getElementById('yourmessageelement').innerHTML =
            "Empty fields not allowed!";
    }
}

// Event handlers for blur (when an element loses focus)
document.getElementById('cf28').onblur = function() {
    validate(this);
}

document.getElementById('city3').onblur = function() {
    validate(this);
}

如果您不希望用户提交包含空字段的表单,则需要使用以下代码行disabled提交按钮:

document.getElementById('yoursubmitbutton').disabled = 'disabled';

像JQuery这样的图书馆会对此有所帮助,但它们有一个学习曲线,而且知道如何自己做这些事情也很好。