Form's input default text - javascript

I desperately need to have my search form's default input text to change based on the user's selection in the form's select input. The current default input text is Enter Keywords… and stays the same no matter what option is selected. What I want, for example, is when the user selects "Employee Directory" to have the default input text for the search field to change to Enter Employee's First Name…
This is the desired input fields for each selection:
"Website" = Enter Keywords…
"Employee Directory" = Enter Employee's First Name…
"Publications Center" = Enter Publication's Information…
Here is my code as it sits currently:
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var submitto = sf.engines.options[sf.engines.selectedIndex].value + escape(sf.s.value) + ((sf.engines.selectedIndex=='1')?('&cat=29'):(''));
window.location.href = submitto;
return false;
}
</script>
<form name="searchform" class="search" method="get" onSubmit="return dosearch();">
<select class="engines" name="engines" id="el08">
<option value="/?s=" selected>Website</option>
<option value="/?s=">Publications Center</option>
<option value="/employee-directory?query=name&contact_dir_s=">Employee Directory</option>
</select>
<input name="s" class="input" type="text" value="Enter Keywords..." onfocus="if (this.value == 'Enter Keywords...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter Keywords...';}" size="18" maxlength="50">
<input type="submit" name="searchsubmit" class="button" value="Go" />
</form>
Anybody with the expertise to help code this or offer suggestions, please do! Cheers!

Updated with code that actually works (only tested in IE). This version notes when the selected search option changes and then updates the input if it was displaying the default prompt that went with the previously selected search option.
<body onload="setDefault();">
<form name="searchform" class="search" method="get" onSubmit="return dosearch();">
<select class="engines" name="engines" id="el08" onchange="setDefault();">
<option value="/?s=" selected>Website</option>
<option value="/?s=">Publications Center</option>
<option value="/employee-directory?query=name&contact_dir_s=">Employee Directory</option>
</select>
<input name="s" id="searchBox" class="input" type="text" value="" onfocus="myFocusHandler(this);" onblur="myBlurHandler(this);" size="18" maxlength="50">
<input type="submit" name="searchsubmit" class="button" value="Go" />
</form>
</body>
<script>
function myFocusHandler(textField) {
if (textField.value == defText)
textField.value = "";
}
function myBlurHandler(textField) {
if (textField.value == "")
textField.value = defText;
}
var defText;
var defOptions = {
"Website" : "Enter keywords...",
"Employee Directory" : "Enter employee's first name...",
"Publications Center" : "Enter Publication's Information..."
// and any other options you may need
};
function setDefault() {
var sel = document.getElementById("el08"),
input = document.getElementById("searchBox"),
prevDefText = defText;
defText = defOptions[sel.options[sel.selectedIndex].text] || "Enter search term...";
if (prevDefText == undefined || input.value == prevDefText)
input.value = defText;
}
</script>
Could cut down on use of globals by using a variation of the module pattern or something, but that's an issue for another day.

Related

HTML - Input DataList - Check Value is in the List

I want to check if the Value enter in the input is in the datalist.
If not i inform that the value is not in the list, I write something but the submit is done anyway, i miss something ?
Edit: I edit to have a trial form. If i enter productD the submit can't not be done becuase is not in the list defined.
<tbody>
<div class="fichetechniquediv">
<form action="{% url 'createdfichetechnique' %}" method='post' onclick="return myCheckFunction(this)">
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlist" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="productA">productA</option>
<option value="productB">productB</option>
<option value="productC">productC</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
</div>
</tbody>
<script>
function myCheckFunction(form) {
var list = document.getElementsById("productslist");// get the values that are currently under the datalist tag in option tags
var val = document.getElementsByName("Product");// get the user input
if( list.include(val)){ // compare the options with the user input
submit(form)}// if one is equal with the user input submit the form with the method submit();
else{
return false// else don't submit the form, the user will have to change his input
}
}
</script>
Example productD
const list = document.querySelector("#productslist")
const btn = document.querySelector(".buttonsave")
console.log(list.options.length)
if(list.options.length <= 0 ){
btn.disabled = true
}else {
btn.disabled = false
}
Check if is any products. If the script can't see any products disable the button to send. I hope I helped
You cannot use include for DOM elements like you do.
Also you have duplicate IDs
Instead do this:
const list = document.querySelectorAll("productslist option")
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = document.getElementById("productlistInput").value
const found = [...list].find(opt => opt.value===val)
if (!found) {
alert("Please choose an existing value");
e.preventDefault();
}
})
<form id="myForm" action="..." method='post'>
<h1>Create the technical Sheet</h1>
<br><br>
<div class="divlot">
<label for="lot">Enter your Lot:</label>
<input type="text" id="lot" name="lot" required minlength="7" oninput="this.value = this.value.toUpperCase()">
</div>
<br><br>
<div class="divproduct">
<label for="productlist">Enter or Select Product:</label>
<input type="text" name="Product" id="productlistInput" list="productslist" label="'Enter or Select your Product:">
<datalist id="productslist">
<option value="prod1">Product 1</option>
<option value="prod2">Product 2</option>
</datalist>
</div>
<br><br>
<input class="buttonsave" type="submit" value="Create" name="submit">
</form>
There are two things going wrong in this:
document.getElementsById("productslist"); is incorrect. The function is getElementById(...)
document.getElementById("productslist"); will get you an HTML nodes, not the values.
One of the ways to get the values is:
const values = [];
Array
.from(document.getElementById("productslist").options)
.forEach((option) => {
values.push(option.value);
}
Now that you have the values in the values array, you can look it up to check if the value is already present.

Second time button click is not getting new form fields value

I have been trying to validate my form fields and showing alert if any of this fields are empty. But after that if user enters the value in that field and than when they click submit button again it keeps showing the error alert even if there are no fields empty anymore.
I have tried following code and found that it works perfectly fine for the first time that is - if there are any empty fields, it will show the error alert. But after that if user enters the value in that field and then again click submit, it's not updating the entered value in jquery and keep showing null value and that is why it's keep showing error alert. I am not able to find any error. Any help would be appreciated. I have tried following code:
<form id="desc-form" action="addRecords.php" method="POST" enctype="multipart/form-data">
<div class="question-input">
<textarea required placeholder="Write description here..." name="desc" id="desc" rows="5" cols="50"></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'desc' );
</script>
<select id="select-gender" name="gender">
// have few options
</select>
<input type="radio" name="subscribe" value="1"> Yes
<input type="radio" name="subscribe" value="2"> No
<a id="submit-btn" class="btn btn-submit">Submit</a>
</div>
</form>
<script type="text/javascript>
$(".btn-submit").click(function() {
var desc = CKEDITOR.instances['desc'].getData();
if (desc === "" || $.trim($("#select-gender").val()) === "" || $.trim($('input[name=subscribe]:checked').val()) != 1) {
alert("Please enter all mandatory details!");
} else {
$("#desc-form").submit();
}
});
</script>
So this code is working when there is empty field, but once any value is entered in all the empty field and when the button is clicked again, it still shows the error alert. I know I am missing minor thing, but not getting it. Any help is appreciated. TIA
$(document).on("click",".btn-submit", function() {
var text = $(document).find('#desc');
var radio = $(document).find('input[name="subscribe"]');
var gender = $(document).find('#select-gender option:selected')
if(text.val() == "" || radio.is(':checked') == false || gender.val() == 'Select') {
alert('Please enter all mandatory details!')
}else{
alert('submit data')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<form id="desc-form" action="addRecords.php" method="POST" enctype="multipart/form-data">
<div class="question-input">
<textarea required placeholder="Write description here..." name="desc" id="desc" rows="5" cols="50"></textarea>
<select id="select-gender" name="gender">
<option hidden>Select</option>
<option value="1">MALE</option>
<option value="2">FEmale</option>
</select>
<input type="radio" name="subscribe" value="1"> Yes
<input type="radio" name="subscribe" value="2"> No
<a id="submit-btn" class="btn btn-submit">Submit</a>
</div>
</form>

How to make html <input> tag with pre-written data

I'm working on a project, and for testing it I need to fill in a large amount of 'input' elements every time when reloading the page. I'm filling in the same numbers every time, so I need 'input' elements to somehow 'remember' the value they were given.
I've seen an example with 'autocomplete' attribute, but then I have to choose the value from a drop box for each input element, so that won't help me.
Is there any way I can code the input tag with pre-written data? Or maybe using javascript?
With jQuery, you can write a plugin to set the input of fields based on data.
You can do the same without jQuery, but you need to find all inputs, textareas, selects, etc. and filter the other junk out of the form before setting values.
Check out this question for more tips: Using jQuery and JSON to populate forms?
(function($) {
$.fn.populateData = function(data) {
var $form = this;
$.each(data, function(key, value) {
$('[name=' + key + ']', $form).val(value);
});
}
})(jQuery);
var pocForm = document.forms['poc-form'];
var pocFormData = {
fname : 'John',
lname : 'Doe',
dob : '1970-12-25'
};
$(pocForm).populateData(pocFormData);
.form-field {
margin-bottom: 0.25em;
}
.form-field label {
display: inline-block;
width: 6em;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="poc-form">
<div class="form-field">
<label for="poc-fname">First Name:</label>
<input type="text" id="poc-fname" name="fname" />
</div>
<div class="form-field">
<label for="poc-lname">Last Name:</label>
<input type="text" id="poc-lname" name="lname" />
</div>
<div class="form-field">
<label for="poc-dob">Date of Birth:</label>
<input type="date" id="poc-dob" name="dob" />
</div>
</form>
here the unput value
<form >
First name: <input type="text" name="fname" value="John"><br>
Last name: <input type="text" name="lname" value="Doe"><br>
</form>
In your input you can use the value tag and set the default value.
<input type="text" name="example" value="Value Goes Here">
You can more or less tell autocomplete how to work: https://html.spec.whatwg.org/multipage/forms.html#autofill
But it still leaves it up to the browser.
A better option is datelist, giving you a text-input with predefined options for autocomplete and an dropdown-menu.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" />
</label>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
<option value="Microsoft Edge">
</datalist>
EDIT:
After reading your question again, I realized that this isn't very good for your use-case. Sorry.
In that case I'd just go with a single line of jQuery:
$('input[type="text"]').val('Hello world') ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="t1" />
<input type="text" name="t2" />
<input type="text" name="t3" />
<input type="text" name="t4" />
<input type="text" name="t5" />
<input type="text" name="t6" />
<input type="text" name="t7" />
with Javascript, you can use static text in strings:
var mystring = "This is my string of text";
var anotherString = "A second string of text";
var myInputs = document.getElementsByTagName("input");
myInputs[0].value = mystring;
myInputs[1].value = anotherString;
If you need the text to be from user entered data, you need to first save the text:
tx = myInputs[0].value
localStorage.setItem("item_name", tx);
//note: you would need to use a keyup event or button to save the data as the user types or clicks the button. Also look in to JSON "stringify" and "parse" to save more complex items.
After you have saved the data you wished, call it and point it to the input you wish.
var savedTx = localStorage.getItem("item_name");
if (savedTx) {//it's important to look for the data first to avoid errors
myInputs[0].value = "My data: " + savedTx + "!";
}

Using jQuery to Populate Data from More Than One Select Control

Anytime a person gets executed, I notify the Judge who put him away.
Recently, we have found there is a problem with people putting down the wrong Executioner. This would not normally be a big deal, but there are some bosses with big families that can make life difficult for the person that performed the execution.
So, the form now needs to be modified to also include an email to the Executioner.
Here are the basics of the webpage:
<form method="post">
Person Executed:
<input type="text" name="_jp2code_killed" value="" size="30" />
<br />
<input type="hidden" name="_jp2code_name_original_value" id="_jp2code_name_original_value" value="Web Master" />
<input type="hidden" name="_jp2code_mail_original_value" id="_jp2code_mail_original_value" value="no-reply#jp2code.net" /><br />
Judge:
<select name="Judge" id="Judge">
<option value="Neal Barton" _jp2code_judge="NBarton#ketknbc.com">Neal Barton</option>
<option value="Howard Pain" _jp2code_judge="hpain#courtcircuit1.us">Howard Pain</option>
</select>
Executioner:
<select name="Executioner" id="Executioner">
<option value="Joe Byrd" _jp2code_executioner="jbyrd#walls.tx.us">Joe Byrd</option>
<option value="Jim Estelle" _jp2code_executioner="jestelle#tdcj.org">Jim Estelle</option>
</select>
<br />
<input type="submit" value="Submit" />
<br />
debug:
<input type="text" name="_jp2code_debug" id="_jp2code_debug" size="30" /><br />
</form>
With those definitions in place, here is the jQuery (v1.7) that I am trying to get to work:
$(function () {
// Save references to elements
var objName = $('#_jp2code_name_original_value');
if (!objName.attr('_jp2code_custom_parameter') ||
($.trim(objName.attr('_jp2code_custom_parameter')) == '')) {
objName.attr('_jp2code_custom_parameter', objName.val());
}
var objEmail = $('#_jp2code_mail_original_value');
if (!objEmail.attr('_jp2code_custom_parameter') ||
($.trim(objEmail.attr('_jp2code_custom_parameter')) == '')) {
objEmail.attr('_jp2code_custom_parameter', objEmail.val());
}
$('#Judge').each(function () {
$(this).change(function () { // Add OnChange EventHandler
var oItem = $(this); // reference to current element
var oName = $('#_jp2code_name_original_value'); // Save references to names
var oEmal = $('#_jp2code_mail_original_value'); // Save references to emails
if ($.trim(oItem.Val()) != '') {
oName.val(oName.attr('_jp2code_mail_original_value') + ',Judge');
oEmal.val(oEmal.attr('_jp2code_mail_original_value') + ',' + $(this).children(':selected').attr('_jp2code_judge'));
} else {
oName.val(oName.attr('_jp2code_mail_original_value'));
oEmal.val(oEmal.attr('_jp2code_mail_original_value'));
}
$('#_jp2code_debug_name').val(oName.val());
$('#_jp2code_debug_emal').val(oEmal.val());
});
});
});
So, despite my best efforts, a couple of things aren't working:
My debug boxes that should be getting the people's names and email addresses is not working. Those debug boxes should always at least include the Web Master name and email address, then append the person's name and address when they are selected. I can't seem to get past that.
Once that is working, how would I add the logic functioning, then I need to include both names and both email addresses from the select boxes.
Here is where I have been fiddling with this:
http://jsfiddle.net/jp2code/c5Q2V/
I solved it.
JS Fiddle: http://jsfiddle.net/jp2code/wunC2/1/
I added a custom attribute to my elements with "Web Master" or the default email address to the HTML:
<form method="post">
Person Executed: <input type="text" name="_jp2code_killed" value="" size="30"/>
<br/>
<input type="hidden" name="_jp2code_name_original_value" id="_jp2code_name_original_value" _jp2code_name_original_value="Web Master" />
<input type="hidden" name="_jp2code_mail_original_value" id="_jp2code_mail_original_value" _jp2code_mail_original_value="norsvp#mail.com" /><br/>
Judge:
<select name="Judge" id="Judge">
<option value="First1 Judge1" _jp2code_judge="judge1#mail.com">First1 Judge1</option>
<option value="First2 Judge2" _jp2code_judge="judge2#mail.com">First2 Judge2</option>
</select>
Executioner:
<select name="Executioner" id="Executioner">
<option value="First1 Exec1" _jp2code_executioner="exec1#mail.com">First1 Exec1</option>
<option value="First2 Exec2" _jp2code_executioner="exec2#mail.com">First2 Exec2</option>
</select>
<br/>
<input type="submit" value="Submit" />
<br/>
debug: <input type="text" name="_jp2code_debug_name" id="_jp2code_debug_name" size="50" /><br/>
debug: <input type="text" name="_jp2code_debug_emal" id="_jp2code_debug_emal" size="50" /><br/>
</form>
For the jQuery, I trimmed it down to a function that was passed to both Select controls, and I had to call the function once so the data would be pre-populated:
$(function() {
function jp2code_get_data() {
var obj1 = $('#_jp2code_name_original_value');
var val1 = obj1.attr('_jp2code_name_original_value');
val1 += ','+$('#Judge').children(':selected').val();
val1 += ','+$('#Executioner').children(':selected').val();
var obj2 = $('#_jp2code_mail_original_value');
var val2 = obj2.attr('_jp2code_mail_original_value');
val2 += ','+$('#Judge').children(':selected').attr('_jp2code_judge');
val2 += ','+$('#Executioner').children(':selected').attr('_jp2code_executioner');
obj1.val(val1);
obj2.val(val2);
$('#_jp2code_debug_name').val(obj1.val());
$('#_jp2code_debug_emal').val(obj2.val());
}
$('#Judge, #Executioner').each(function () {
$(this).change(jp2code_get_data);
});
jp2code_get_data();
});
This is probably not helpful to everyone, but I like to post the solution if others have the same problem.

Search box active when visiting website.

I have a search box that I would like to make active when the customer visits my web page.
My HTML is:
<form class="form-search top-search" action="Search.aspx" onsubmit="return validateSearch(this);" method="GET">
<input type="text" class="input-medium search-query yui-ac-input" name="ss" id="ss" placeholder="Search and find it fast" title="Search and find it fast" onblur="if (this.value == '') { this.value = 'Search and find it fast'; }" onfocus="if ((this.value == 'Search and find it fast')||(this.value == 'Search and find it fast')) { this.value = ''; }" onkeypress="if ((this.value == 'Please enter a keyword or item #')||(this.value == 'Search and find it fast')) { this.value = ''; } else{ document.getElementsByName('ss')[0].style.color='black'; }" autocomplete="off">
<input type="submit" title="Search" class="btn btn-orange SearchButton" value="Search">
</form>
I'm just wanting to default the user into the field, like how Amazon defaults you into their search box.
You can use the HTML5 autofocus attribute:
<input type="text" autofocus>
You can use .focus() to focus the input
$(function () {
$('#ss').focus();
});
DEMO
Pure Javascript solution, works IE6+ and any other browser.
Put this before body end tag
<script type="text/javascript">
var obj = document.getElementById("ss");
obj.focus();
</script>
On browsers, that support html5, you can use autofocus attribute inside input.
<input autofocus type="text" class="input-medium search-query yui-ac-input" name="ss" id="ss" placeholder="Search and find it fast" title="Search and find it fast" autocomplete="off" />
You can use any of these options After Page Load.
$('#ss').focus();
$('#ss').select();
$('#ss').trigger('focus');
$('#ss').trigger('click');
For Example:
$(document).ready(function(){
$('#ss').trigger('click');
});

Categories