How to change placeholder and name from select option dynamically using jQuery - javascript

if i need to edit my question please state so before down voting.
I'm creating a form that when an option selected. a form will appear depends on the option selected. How do i dynamically change placeholder and name. Also if the option is selected multiple times the placeholder and name will increment like
placeholder="holder1" name="name1"
placeholder="holder2" name="name2"
here's my code:
Twig file
<select class="form-control" id="collaterals" name="loan_type_id" required>
<option disabled value="0" selected}>-- Select Collateral --</option>
<option value="" id="veh_coll">Vehicle</option>
<option value="" id="hal_coll">House and Lot</option>
<option value="" id="lot_coll">Lot</option>
</select>
Jquery
jQuery(document).on('click',"#removeThis",function(e){
jQuery(this).closest('tr').remove();
e.preventDefault();
});
jQuery("#addType").click(function() {
var selectedType = jQuery('#collaterals :selected').text();
jQuery("#nfo").clone().appendTo('tbody');
jQuery("#addTypeText").val(selectedType);
jQuery("#nfo").removeClass("hidden-xs-up");
});
I need the placeholder and the name to be dynamic depends on the option i selected and also making the name increment for example name="vehicle1" if add another option it will be name="vehicle2"

I am self-taught so someone please show me a better way if possible.
Create a counter with global scope:
i = 0
(inside a function)
Window[i] = 0
Increment when they choose an option:
Window[i] ++
When you want to set the name and placeholder:
$(input).attr("placeholder", newValue + window[i])
$(input).attr("name", newValue + window[i])

Related

Pass field title attribute through onchange another field

Here is my code.
//I want to pass field1 selected option's title through onkeyup
function select_data(field1) {
alert(field1);
}
<select id="field1" onchange="select_data(this.options[this.selectedIndex].title)">
<option value="213" title="1">A</option>
<option value="214" title="12">AB</option>
<option value="215" title="13">AC</option>
</select>
<input type="text" id="vat" onkeyup="select_data()" />
I want to get the selected option's title by onkeyup from text field.
Advance thanks for help.
let selText = document.getElementById('field1').options[document.getElementById('field1').selectedIndex].title
You want this:
<script>
//I want to pass field1 selected option's title through onkeyup
function select_data(field1) {
//alert(field1);
alert(field1.options[field1.selectedIndex].title);
}
</script>
<select id="field1" onchange="select_data(this.options[this.selectedIndex].title)">
<option value="213" title="1">A</option>
<option value="214" title="12">AB</option>
<option value="215" title="13">AC</option>
</select>
<input type="text" id="vat" onkeyup="select_data(document.querySelector('#field1'))" />
You can achieve this by selecting the select inside of the function instead of passing all that parameter by inline HTML (which is not advisable).
So, use querySelector() get the select, get the current selected index and title, show it.
THe below method can be called from everywhere and it will work, since all job of getting the title is inside the function
Note: Always when possible, avoid assing listeners in the HTML, it's not the right place and it is also obstrusive and not easy to maintain, opt for adding listeners in the JS/script part, also avoid passing parameters in HTML inline listeners.
//I want to pass field1 selected option's title through onkeyup
function select_data() {
let select = document.querySelector("#field1")
let title = select.options[select.selectedIndex].title;
console.log(title)
}
<select id="field1" onchange="select_data()">
<option value="213" title="1">A</option>
<option value="214" title="12">AB</option>
<option value="215" title="13">AC</option>
</select>
<input type="text" id="vat" onkeyup="select_data()" />

How to set default value in input datalist and still have the drop down?

I am using the datalist HTML property to get a drop down inout box:
<input list="orderTypes" value="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The problem is that now I have to clear the input box to view all the drop down values. Is there a way to have a default value but still view all the values in the datalist when the drop down icon is clicked?
I have the same problem.
I just simple added placeholder with the default data.
In your example:
<input list="orderTypes" name="orderType" id="orderType" placeholder="Book" />
I listen submit event. If the input value is empty, I use Book as default value, otherwise I use the given value...
$("#mySubmitButton").click(() => {
// use event prevent here if need...
const orderType = $("#orderType").val() || "Book";
console.log(orderType);
});
I know of no way to do this natively. You could make a "helper" div to use when the input field has value. I couldn't hide the native drop down so I renamed the ID. Uses jQuery.
html
<input list="orderTypes" id="dlInput">
<div id="helper" style="display:none;position:absolute;z-index:200;border:1pt solid #ccc;"></div>
<datalist id="orderTypes" style="z-index:100;">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
script
$(function(){
// make a copy of datalist
var dl="";
$("#orderTypes option").each(function(){
dl+="<div class='dlOption'>"+$(this).val()+"</div>";
});
$("#helper").html(dl);
$("#helper").width( $("#dlInput").width() );
$(document).on("click","#dlInput",function(){
// display list if it has value
var lv=$("#dlInput").val();
if( lv.length ){
$("#orderTypes").attr("id","orderTypesHide");
$("#helper").show();
}
});
$(document).on("click",".dlOption",function(){
$("#dlInput").val( $(this).html() );
$("#helper").hide();
});
$(document).on("change","#dlInput",function(){
if( $(this).val()==="" ){
$("#orderTypesHide").attr("id","orderTypes");
$("#helper").hide();
}
});
});
jsFiddle
Is this what you trying to do?
var demoInput = document.getElementById('demoInput'); // give an id to your input and set it as variable
demoInput.value ='books'; // set default value instead of html attribute
demoInput.onfocus = function() { demoInput.value =''; }; // on focus - clear input
demoInput.onblur = function() { demoInput.value ='books'; }; // on leave restore it.
<legend>(double) click on the input to see options:</legend>
<input list="orderTypes" id="demoInput">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The only "problem" here is that in order to see the options the user have to click the input again so it's like "double-click the input to see options".
Hope that helps.
I would use input's placeholder attribute along with a Javascript code that'll make sure that the field isn't empty upon submission.
Obviously this is just an example, you'll have to modify the submission event.
document.getElementById('submitButton').addEventListener('click', function() {
let inputElement = document.getElementById('myInput');
if (!inputElement.value) {
inputElement.value = 'Book';
}
});
<input id="myInput" list="orderTypes" placeholder="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
<input id="submitButton" type="submit">
I've menaged to get what You described with just <select> + <option> tags instead of <input> + <datalist>:
<select name="sortBY">
<option value="Book">Book</option>
<option value="Copy">Copy</option>
<option value="Page">Page</option>
</select>
Putting it all inside <form></form> tags will send it eg. with POST method with $_POST['sortBY'] value.
If this helps at all:
$('#grouptext').val($('#grouplist option#48').attr('value'));
where '#grouptext' is your text input to which your datalist '#grouplist' is attached, and #48 is the ID you're looking to "pre-select".
here's what my data list looks like, for clarity
worked for me.
In Chrome's console it shows up like this with "option#115", which corresponds to the correct text in the datalist for that "id" (being 115)
set id for your input and with js set default value
<script>
setTimeout(() => {
document.getElementById('orderTypes').value = "Book";
}, 100);
</script>

Html select onchange get custom attribute value set to other input value

onchange I want to get the select option custom attribute and set to the other input's value. Somehow I cannot get the course_price in the input onchange of the select. It only shows the first option value in the input only.
function selectFunction(e) {
var value1 = $("#test").data('typeid'); //to get value
document.getElementById("money").value = value1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" onchange="selectFunction(event)">
<option id="test" data-typeid="<?php echo $row1['course_price']?>"
value="<?php echo $row1['course_id']?>"><?php echo $row1['course_name']?>
</option>
</select>
<input type="number" value="" id="money" class="form-control">
The issue is because the data-typeid attribute is on the selected option, not the select, so your jQuery code is looking at the wrong element. You can fix this by using find() and :selected to get the chosen option before reading the data attribute from it.
Also note that on* attributes are very outdated. You should be using unobtrusive event handlers, something like this:
$(function() {
$('select.form-control').change(function() {
var typeId = $(this).find('option:selected').data('typeid');
$("#money").val(typeId);
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">
In your question you are using #test which is id for all options and so it will always consider first occurance of id test. So do not use same id multiple times on the same DOM, change it to class="test" if you need it, otherwise, you need to target the selected option, and it will not need any id or class. Check here:
var type_id = $('select option:selected').attr('data-typeid');
and assign the variable to input box:
document.getElementById("money").value =type_id;
So the entire updated function will be like this:
function selectFunction(e) {
var type_id = $('select option:selected').attr('data-typeid'); //to get value
document.getElementById("money").value =type_id;
}
Another way to make it:
$(document).on('change', 'select.form-control', function() {
var r = $('select.form-control option[value="'+$(this).val()+'"]').attr("data-typeid")
$("#money").val(r)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected disabled>-- Select one --</option>
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">

How to assign a different name for each radio input group

I'm looking for a solution to dynamically change the name for a group of input radio buttons.
I'm creating a travel itinerary where the user selects "domestic" or "international." That selection will hide/show the appropriate state/country dropdown below. There could be multiple destinations, therefore, I need multiple state/country selectors. The problem I'm running into is that all the inputs have the same name, so only one button will display as "checked" at any given time.
The code snippet will come in via an .ssi, so I can't just hard code the input name. I need a JavaScript/jQuery method of dynamically changing it as more destinations are added. The default is "destination." I'd like it to be "destination1," "destination2," etc. for each radio button group.
Here's a very watered-down version of the HTML (Not looking for a debate on table-based layouts. My team has already hashed that out):
<table>
<tbody>
<tr>
<td colspan="2">
<input type="radio" checked="checked" name="destination" class="js-trigger" data-destination="stateForm"> Domestic
<input type="radio" name="destination" class="js-trigger" data-destination="countryForm"> International
</td>
</tr>
<tr>
<td>Destination:</td>
<td>
<form class="stateForm list">
<select name="State" id="state-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
<option value="Select State" selected="selected"></option>
<option value="Alabama" data-alternative-spellings="AL">Alabama</option>
<option value="Alaska" data-alternative-spellings="AK">Alaska</option>
<option value="Etc" data-alternative-spellings="Etc">Etc</option>
</select>
</form><!-- End State Form -->
<form class="countryForm list">
<select name="Country" id="country-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
<option value="Select Country" selected="selected"></option>
<option value="Afghanistan" data-alternative-spellings="AF افغانستان">Afghanistan</option>
<option value="Åland Islands" data-alternative-spellings="AX Aaland Aland" data-relevancy-booster="0.5">Åland Islands</option>
<option value="Etc" data-alternative-spellings="Etc">Etc</option>
</select>
</form><!-- End Country Form -->
</td>
</tr>
</tbody>
</table>
Here's my fiddle: http://jsfiddle.net/Currell/9sr5rkjy/2/
I'm a bit of a JavaScript beginner, so forgive me if my process, terminology, or my code is a bit off.
You could re-name them by adding this:
var counter = 0;
$('table').each(function(){
$(this).find('input[type=radio]').attr('name','destination'+counter);
counter++;
})
jsFiddle example
Update: I just noticed that all your select elements are duplicating name and ID attributes. To fix that you can change the code to:
var counter = 0;
$('table').each(function () {
$(this).find('input[type=radio]').attr('name', 'destination' + counter);
$(this).find('select').eq(0).attr({
'name': 'State' + counter,
'id': 'state-selector' + counter
});
$(this).find('select').eq(1).attr({
'name': 'Country' + counter,
'id': 'country-selector' + counter
});
counter++;
})
jsFiddle example
You need to change them in groups (currently grouped in TDs):
$("td:has(':radio')").each(function(index){
var $radio = $(this).find(':radio');
$radio.attr("name", $radio.attr('name') + index);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/9sr5rkjy/5/
This will rename each set to name="destination0", name="destination1" etc.
You have duplicated ID fields too, which is invalid HTML, so you need to apply a similar fix to those. jQuery and Javascript can only find the first occurence of an ID as browsers use a fast lookup dictionary (with only one element stored against each ID value).

Set option value with getElementsByName()

Having this fieldset:
<fieldset>
<legend>[*death]</legend>
<select name=death style="width: 120px">
<option value=Dead>[*died]
<option value=NotDead>[*alive]
<option value="" selected>-
</select>
</fieldset>
i want to set the [2].value to "-".
i have tried without any success:
document.getElementsByName('death')[2].checked = 'true';
document.getElementsByName('death')[2].value = '-';
Same kind of code works fine for radio boxes, checked boxes or other inputs in the form. How to do it with the option select (which is not an input)?
Thanks
[EDIT] of course, appropriate fieldset is:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
thanks.
It's a little bit unclear what you're asking. Are you simply asking to make the option at index 2 selected?
document.getElementsByName('death')[0].selectedIndex = 2;
Or, are you asking to change the value of option at index 2?
var d = document.getElementsByName('death')[0];
d.options[2].value = '-';
You need to manipulate the selected property of your select object, try
document.getElementsByName('death')[0].selectedIndex = 1;
In english, this reads "set the selected option to the second option in the first element in the document with name 'death'".
Fixing your HTML might make the results of your javascript more predictable. Close your tags, quote your attribute values, as follows:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
you can do this using jQuery... it's easy...
j("#death").val(2)
document.getElementsByName('death')[2] returns the third element named death - but you only have one element with that name. Instead, you want the first element named death (i.e. the one at index 0), and then you want its third option: document.getElementsByName('death')[0].options[2].value = ...
Here's an alert example of how to access your specific option values with getElementsByName
alert(document.getElementsByName('death')[0].options[0].value); // will return Dead
alert(document.getElementsByName('death')[0].options[1].value); // will return NotDead

Categories