I'm looking to put together a form on our website that would feature a preview sentence based on a series of input boxes and drop down menus. I know how to change text based on the input of a drop down menu. However, how do you change the entire sentence (not just the variable) if something in particular is selected? Do you know how to accomplish something like this?
For example (3 input questions to make up a sentence):
1) School name (text field)
2) What would best describe you? (drop down menu)
Sophmore
Senior
Professor
Masters Degree Holder
3) What are you [studying, teaching, have studied]? (text field)
If 'Sophmore' is selected, the preview sentence should look like this:
[Sophmore] at [Harvard] studying [Math]
But if the user selects 'professor', then it would go like this:
[Professor] at [Harvard] teaching [Math]
And if the user selects 'Masters Degree Holder', it would go like this:
[Masters Degree Holder] for [Math] at [Harvard]
Any ideas on how to make this happen?
Thanks!
Something like this would work. You can monitor the inputs one at a time and set the text of the sentence. Or perhaps you want to use a complete button and just build it at the end. Either way the concepts are the same. In your html assign id's to the inputs. For your sentence you can use spans with ids. Then use document.getElementById to retrieve the values of the inputs. When they are changed update the sentence. You can use innerHTML to set a new value on an element.
http://jsfiddle.net/pktMJ/
<select id="description">
<option></option>
<option>Sophmore</option>
<option>Senior</option>
<option>Professor</option>
</select>
<br />
<input id="school" type="text" />
<br />
<input id="study" type="text" />
<div >
<span id="a"></span> at <span id="b"></span> studying <span id="c"></span>.
</div>
document.getElementById('description').onchange = function() {
document.getElementById('a').innerHTML = this.value;
var verb = '';
switch (this.value) {
case 'Professor':
verb = 'teaching';
break;
case 'Sophomore':
verb = 'studying';
break;
case 'Senior':
verb = 'studying';
break;
}
document.getElementById('d').innerHTML = verb;
};
document.getElementById('school').onblur = function() {
document.getElementById('b').innerHTML = this.value;
};
document.getElementById('study').onblur = function() {
document.getElementById('c').innerHTML = this.value;
};
Related
I want to show message required when user don't set a choice.
This is my code:
var options = document.querySelectorAll('.myOptions');
var selecText = document.querySelector('.selectFeld>p');
var mylist = document.querySelector('.list_contrat');
//var iconSelect = document.querySelector(".icon_typeCont_rota");
var valueTypeContra = document.querySelector('#typecontrat');
for(option of options) {
option.onclick = function() {
mylist.classList.toggle('myhide');
//iconSelect.classList.toggle('myRotate');
selecText.innerHTML = this.textContent;
valueTypeContra.value = this.getAttribute('data-value'); // get value select option
}
}
<div class="selectFeld" title="Type de contrat">
<input type="text" name="typeContrat" id="typecontrat" class="d-none" required>
<p>Type de contrat</p>
<img src="icon_form/Icon_contrat_deroulant.png" alt="" class="icon_select">
</div>
<ul class="container-optionSelec list_contrat myhide">
<li class="myOptions" data-value="redaction"><p>Redaction</p></li>
<li class="myOptions" data-value="assistance"><p>Assistance</p></li>
</ul>
It's a custom select option, the code set the value for the input displayed none
Since you're not using a standard form element you're not able to use the standard required attribute, and therefore don't have the standard help features that goes along with it. And adding required to your input field does not present the built-in help message because you are hiding it.
You need to use Javascript to program a custom "required" message to go along with your custom form input mechanism. Naturally there are a number of ways to accomplish this, and present an error message to your user. What do you suppose works best for your users?
Upon first glance...
Remove the ineffective required attribute from the input element. Change the input to a hidden type, to avoid using css to hide it. And add a note to the instructions letting your users know ahead of time the selection is necessary to proceed.
Add a submit event handler to the form to capture submission and have an opportunity to validate the form. In the handler check the (now hidden) input field for an empty string indicating the custom selection mechanism has not been used. If the input value is empty, emphasize the instructions, and provide the user an error message.
For example:
var options = document.querySelectorAll('.myOptions');
var selecText = document.querySelector('.selectFeld>p');
var mylist = document.querySelector('.list_contrat');
var valueTypeContra = document.querySelector('#typecontrat');
for (option of options) {
option.onclick = function() {
selecText.style.color = 'black'; // restore black color to instruction
selecText.innerHTML = this.textContent;
valueTypeContra.value = this.getAttribute('data-value');
}
}
// GET FORM AND ADD SUBMIT EVENT HANDLER
document.querySelector('form').onsubmit = function () {
// check if "typeContrat" is equal to an empty string
if ( "" === this.elements['typeContrat'].value ) {
// emphasize the instruction label
selecText.style.color = 'red';
// provide the user and alert message
alert('Veuillez sélectionner type de contrat');
// prevent the form from being submitted
return false;
}
// if "typeContrat" is not an empty string submit the form
else { return true; }
}
<form>
<div class="selectFeld" title="Type de contrat">
<input type="hidden" name="typeContrat" id="typecontrat" class="d-none" value="">
<p>Type de contrat (required)</p>
</div>
<ul class="container-optionSelec list_contrat myhide">
<li class="myOptions" data-value="redaction">
<p>Redaction</p>
</li>
<li class="myOptions" data-value="assistance">
<p>Assistance</p>
</li>
</ul>
<input type="submit">
</form>
However, there are many user interface approaches and programming mechanisms to accomplish this, so first determine what works best for your users, supports your application purpose, goals, and look, meets your security needs—and do that.
I have a form where users can create recipes. I start them off with one ingredient field (among others) and then use .append() to add as many more as they want to the div container that holds the first ingredient. The first input field has an id of IngredientName1 and dynamically added input fields are IngredientName2, IngredientName3, etc.
When they start typing in the input field, I pop a list of available ingredients filtered by the value they key into IngredientNameX. When they click on an ingredient in the list, it sets the value of the IngredientNameX field to the text from the div - like a search & click to complete thing. This all works very well; however, when you add IngredientName2 (or any beyond the one I started them with initially) clicking on an available ingredient sets the values of every single IngredientNameX field. No matter how many there are.
I hope this is enough context without being overly verbose, here's my code (I've removed a lot that is not relevant for the purpose of posting, hoping I didn't remove too much):
<div id="ingredientsContainer">
<input type="hidden" id="ingredientCounter" value="1">
<div class="ingredientsRowContainer">
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName1" placeholder="Ingredient" id="IngredientName1" data-ingID="1"><span class="focus-border"></span></div>
</div>
<input type="hidden" name="Ingredient1ID" id="Ingredient1ID">
</div>
<script>
$(document).ready(function(){
$(document).on('keyup', "[id^=IngredientName]",function () {
var value = $(this).val().toLowerCase();
var searchValue = $(this).val();
var valueLength = value.length;
if(valueLength>1){
var theIngredient = $(this).attr("data-ingID");
$("#Ingredients").removeClass("hidden")
var $results = $('#Ingredients').children().filter(function() {
return $(this).text() === searchValue;
});
//user selected an ingredient from the list
$(".ingredientsValues").click(function(){
console.log("theIngredient: "+theIngredient);//LOGS THE CORRECT NUMBER
var selectedIngredientID = $(this).attr("id");
var selectedIngredientText = $(this).text();
$("#IngredientName"+String(theIngredient)).val(selectedIngredientText);//THIS IS WHAT SETS EVERYTHING WITH AN ID OF IngredientNameX
$("#Ingredient"+String(theIngredient)+"ID").val(selectedIngredientID);
$("#Ingredients").addClass("hidden");
});
$("#Ingredients *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$("#Ingredients").addClass("hidden")
}
});
$("#AddIngredient").click(function(){
var ingredientCounter = $("#ingredientCounter").val();
ingredientCounter++;
$("#ingredientCounter").val(ingredientCounter);
$('#ingredientsContainer').append('\
<div class="ingredientsRowContainer">\
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName'+ingredientCounter+'" placeholder="Ingredient" id="IngredientName'+ingredientCounter+'" data-ingID="'+ingredientCounter+'"><span class="focus-border"></span></div>\
</div>\
<input type="hidden" name="Ingredient'+ingredientCounter+'ID" id="Ingredient'+ingredientCounter+'ID">\
');
});
});
</script>
[UPDATE] I realized the problem is happening because the function is running multiple times. I assume this happening because I'm calling a function on keyup of a field whose id starts with IngredientName so when one has a key up event, all existing fields run the function. How do i modify my:
$(document).on('keyup', "[id^=IngredientName]",function () {
to only run on the field with focus?
reposting for simplicity. i want to have the text users enter into an input to replace the label text of another form's input. Additionally, the form is a plugin which doesn't let me attach an id to the specific label tag of the text i want to change. how can i do this, in vanilla javascript please.
the input users put text into:
<input class="charInput" id="name1" type="text" onKeyUp="change1(this)" >
the form label i want to change the text in (p.s: cant use the class(not unique to this label), cant add id):
<div id="frm_field_53_container" class="frm_form_field form-field frm_top_container">
<label class="frm_primary_label" for="field_inputactor1">
TEXT TO REPLACE
<span class="frm_required"></span>
</label></div>
Maybe it is not the best solution, but it is a solution that works in Firefox and Chrome (not tested under IE)
findLabelToChange = function() {
var div = document.getElementById("frm_field_53_container");
return div.querySelector("label");
};
customizeText = function(text) {
return text + ' <span class="frm_required"></span>';
};
change1 = function() {
var label = findLabelToChange();
var text = document.getElementById("name1").value;
label.innerHTML = customizeText(text);
};
you can see a example in this feedle
http://jsfiddle.net/HAK5X/1/
Here is a fiddle.
It is one line of code.
http://jsfiddle.net/te3jv/6/
function change1(myInput){
document.getElementById('frm_field_53_container').querySelector("label").innerHTML =myInput.value;
}
Alternatively add <span class="frm_required"></span> to the end of HTML reassignment to keep your empty (but required?) span.
I am hoping for some insight on the best way to accomplish the following. I want to create a form that will allow for more fields to be added when a + or add button is clicked. So for example the user would fill out a text field lets call it "Description" and then next to it another field called "Unit number". I want to allow for multiple "Description" and "Unit number" fields without submitting the form after each entry, but for the sake of keeping the site looking "Clean" I don't want there to be several duplicate fields if the user only needs to enter information into one of them. I was thinking about using JavaScript to hide the additional fields by just setting display:none. Is this a good/efficient solution? Is there a better solution? I am new to programming so take it easy if you feel this is a dumb question.
The best way to do this is to make your fields and put them in a div and then hide it. Use jQuery to .clone your first row and then update the field names any time the user clicks an add link.
You can use a templating library like mustache or handlebars. You can also do this using jQuery. My approach would be to generate new elements on the fly. I won't hide it so that the user can see if he is already inputting duplicate. But if you want to make your markup cleaner, you can also hide the field once the user has already inputted something. So when the user clicks on the add button, you will need to check if the user has actually inputted something, if there is an input, then hide it and then generate a new input again.
If you need a code sample, feel free to ask.
Here's some javascript I wrote on my own site awhile ago:
var SITE = SITE || {};
SITE.fileInputs = function() {
var $this = $(this),
$val = $this.val(),
valArray = $val.split('\\'),
newVal = valArray[valArray.length-1],
$button = $this.siblings('.button'),
$fakeFile = $this.siblings('.file-holder');
if(newVal !== '') {
$button.text('File Chosen');
if($fakeFile.length === 0) {
$button.after('<span class="file-holder">' + newVal + '</span>');
} else {
$fakeFile.text(newVal);
}
}
};
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<span class=\"file-wrapper\"><input type=\"file\" name=\"screenshot[]\" id=\"screenshot\" /><span class=\"button\">Choose a screenshot</span></span>";
document.getElementById(divName).appendChild(newdiv);
counter++;
$('.file-wrapper input[type=file]').bind('change focus click', SITE.fileInputs);
}
}
$(document).ready(function(){
$("#addss").click(function(){
addInput("screenshots");
});
});
Then you can just use the array for the name in the php or whatever else you're using to handle the data.
HTML:
<div id="screenshots">
<span class="file-wrapper">
<input type="file" name="screenshot[]" class="screenshot" />
<span class="button">Choose a screenshot</span>
</span>
</div>
<input type="button" id="addss" value="+Screenshot" class="btn" />
I want to know if its possible to change the name of the input tag with javascript or jquery, for example in this code :
<input type="radio" name="some_name" value="">
I want to change the some_name value when user select this radio button.
the reason what i want to do this is described here : How might I calculate the sum of radio button values using jQuery?
Simply elem.name = "some other name" or elem.setAttribute("name", "some other name") where elem is the element you want to alter.
And to do that on selection, use the onchange event:
<input type="radio" name="some_name" value="" onchange="if(this.selected) this.name='some other name'">
And to apply that behavior to every radio button with that name:
var inputElems = document.getElementsByTagName("input");
for (var i=inputElems.length-1; i>=0; --i) {
var elem = inputElems[i];
if ((elem.type || "").toLowerCase() == "radio" && elem.name == "some_name") {
elem.onchange = function() {
if (this.selected) {
this.name = "some other name";
}
};
}
}
But using jQuery for that is quite easier.
The jQuery way
$('input:radio[name="some_name"]').attr('name', 'new name');
Gumbo has the vanilla JavaScript way covered
Yes, you can change the name of any element with javascript. Keep in mind though that IE 6 and 7 have trouble with submitted forms where the input elements have been tinkered with in javascript (not sure if this exact case would be affected).
$('input:radio[name="some_name"]').attr('name', 'new_name');
Edit: To change it only when it is selected, here is the code for that:
$("input:radio[name='some_name']").click(function() {
if ($(this).attr('checked')) $("input:radio[name='some_name']").attr('name', 'new_name');
else $("input:radio[name='some_name']").attr('name', 'some_name');
});
Sure. If jQuery is your poison, this should do the trick:
$("input[name=some_name]").attr("name", "other_name");
I came up with this:
<input type="radio" name="some_name" value="" id="radios">
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#radios").click(function()
{
$(this).attr("name", "other_name");
});
});
</script>
Trying to change the name attribute of a radio button will cause strange, undesirable behavior in IE.
The best way to handle this is to replace the old radio button with a new one. This post may help you. If you are using jQuery, you can do it with the replaceWith function.
More information about changing name attributes in IE.