How to display a preselected value in a dropdown without 'onchange' - javascript

Currently I have a dropdown in my edit.blade.php
<div class="md-form">
<select id="estado_civil" name="estado_civil" class="mdb-select validate" onchange="editar('estado_civil',$(this).val());">
<option value=""></option>
<option value="1">Soltero(a)</option>
<option value="2">Unido(a)</option>
<option value="3">Casado(a)</option>
</select>
</div>
I needed the dropdown to select/display the value the user had previously chosen and stored in the database. I achieved this using JQuery:
$(document).ready(function() {
var e = $.Event('change');
$('#estado_civil').val('{{$personas->estado_civil}}').focus().trigger(e);
However, this function registers the display of the pre-selected value as a 'change' upon page load. Therefore, it triggers another function I made that notifies the user the value has changed.
Question: Is there a way to select/display the preselected value from the database, without registering it as a change?
Thank you so much!

I'm not super familiar with Laravel but from a quick read of the docs you'd do something like this in the blade:
<option value="1" {{estado_civil) == 1 ? "selected" : ""}}>Soltero(a)</option>
<option value="2" {{estado_civil) == 2 ? "selected" : ""}}>Unido(a)</option>
This uses a ternary to set the selected value of the input.

Related

Angular - my ngIf hides an input-label only once

*ngIf="currentIdea.oetSupportNeeded" I have a dropdown list with 2 values - yes and no, and another input label where you can write freely. I want to show the input-label only when user chose "yes" in the dropdown list and to hide it when "no" is chosen.
My problem is that the following code works only once - when page loads and "no" is chosen, the input label is hidden, but when you choose "yes" and then "no" again, the label shows up and doesn't disappear anymore. I want it to toggle on/off depending on the user's choice
I tried using ngShow, ngHide, [disabled], etc. Nothing helped
<div class="select-wrapper" [ngClass]="{'select-wrapper-blocked': isNotAdmin()}">
<select class="input-control" [(ngModel)]="booleanVariable">
<option value="false">No</option>
<option value="true">Yes</option>
</select>
</div>
</div>
<div class="col form-input" [ngClass]="{'form-input-blocked': isNotAdmin()}">
<p class="input-label">
Some text
</p>
<input *ngIf="booleanVariable" class="input-control" [(ngModel)]="stringVariable" />
</div>
According to the code you shared, the value of your select menu is bound to the booleanVariable property of your component.
Your *ngIf queries another property, so the condition is wrong. You should be checking the booleanVariable in the condition.
Something similar happened to me few hours ago. The problem was that
<option value="false">No</option>
<option value="true">Yes</option>
was wrong. I solved it with
<option [value]="false">No</option>
<option [value]="true">Yes</option>
That's because otherwise Angular does not "analyze" the value of the option but recognizes it as a string.
Use ngModelChange event and make a function to typecast the data.
Check the link for example. Show Hide Field using *ngIf
You are using true and false as strings. You can change the test into your ngIf.
Like
<select [(ngModel)]="foo">
<option [ngValue]="true">true</option>
<option [ngValue]="false">false</option>
</select>
<input *ngIf="foo == true"/>
And to define a default value, you can set the value of foo into the class like
public foo = true;

How do I create a link to pre-select a form option

I have the following code on another webpage on my site with a form (say on page index.html): JSFiddle
<select class="select form-control" id="dropdown" name="dropdown" onchange="showForm()">
i.e a dropdown form.
I want to have a link on another webpage that will go to this page, and have the "Sales" option already selected.
<option value="1">
Sales
</option>
from the drop down menu (instead of the current default option), how do I create this?
Query parameters can be used to achieve the result you want, but you will need to parse the query parameter manually on your current page, since there is no standard JavaScript method for doing it.
You can write the following code on your page to automatically select the option:
$(document).ready(function() {
// Parse your query parameters here, and assign them to a variable named `queryParams`
var option = queryParams.type;
$("#dropdown").val(option);
});
Now you can create an anchor with the URL of this page, e.g. http://yourpage.url?type=1, which will redirect to this page, and will automatically change the value of your dropdown accordingly.
You must add some kind of router functionality with Javascript in your site.
I think the simplest thing you could do it to have a script in that page that checks the url if it has say a #bar hash like so: http://yoursite.com/foo.html#bar.
<script>
// make sure you run this on DOM ready like in $.ready() in jQuery or in a script just before closing the body tag
if(window.location.hash === 'bar') {
// add the selected attribute to the <option> you want
}
</script>
Try with append() function of jquery .and pass this with in onchange function call .And also added with document.ready for create the link on document load with selected value
function showForm(that){
var s = $(that).children('option:selected').text()
$('#link_box').append(''+s+'</br>')
}
$(document).ready(function(){ // for window load
showForm($('select'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group ">
<label class="control-label" for="dropdown">
What can we help you with?
</label>
<select class="select form-control" id="dropdown" name="dropdown" onchange="showForm(this)">
<option value="0" disabled>
Select an option
</option>
<option value="1" selected>
Sales
</option>
<option value="2">
Complaints
</option>
<option value="3">
Queries
</option>
<option value="4">
Ideas
</option>
</select>
</div>
<div id="link_box">
<!-- its a link append box-->
</div>

What is onload() function for forms or select?

I'm trying to find a function in JavaScript that is called everytime when a <form> or <select> is created. Does anyone have a idea?
I want something like:
<body onload="jsFunction();">
More exactly, I need to make a <select> that will be included in many pages, and I want everytime this is loaded, to select one of it's values based on a request variable. So the function that will make the selection must called from this included script and must be included in this script.
I'm using JSP on the server side
This makes no sense. Just set the whole selected attribute programmatically based on the request parameter. Here's an example:
<select name="foo">
<option value="bar" ${param.foo == 'bar' ? 'selected' : ''}>Bar</option>
<option value="baz" ${param.foo == 'baz' ? 'selected' : ''}>Baz</option>
<option value="waa" ${param.foo == 'waa' ? 'selected' : ''}>Waa</option>
</select>
or if you have it in a collection:
<select name="foo">
<c:forEach items="${foos}" var="foo">
<option value="${foo}" ${param.foo == foo ? 'selected' : ''}>${foo}</option>
</c:forEach>
</select>
The same is true for normal inputs:
<input type="text" name="bar" value="${fn:escapeXml(param.bar)}" />
(the fn:escapeXml() is there to prevent XSS attacks)
You could try the "selected" attribute in the option you want to select by default (like suggested here). If you prefer javascript, you'll need to use something like jquery to select select (or populate and select) your tag.
For reference:
<select>
<option>Volvo</option>
<option selected="selected">Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>

Can I apply the required attribute to <select> fields in HTML?

How can I check if a user has selected something from a <select> field in HTML?
I see <select> doesn't support the new required attribute... do I have to use JavaScript then? Or is there something I’m missing? :/
Mandatory: Have the first value empty - required works on empty values
Prerequisites: correct html5 DOCTYPE and a named input field
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
As per the documentation (the listing and bold is mine)
The required attribute is a boolean
attribute.
When specified, the user
will be required to select a value
before submitting the form.
If a select element
has a required attribute specified,
does not have a multiple attribute specified,
and has a display size of 1 (do not have SIZE=2 or more - omit it if not needed);
and if the value
of the first option element in the
select element's list of options (if
any) is the empty string (i.e. present as value=""),
and that
option element's parent node is the
select element (and not an optgroup
element),
then that option is the
select element's placeholder label
option.
The <select> element does support the required attribute, as per the spec:
http://dev.w3.org/html5/spec-author-view/the-select-element.html#the-select-element
Which browser doesn’t honour this?
(Of course, you have to validate on the server anyway, as you can’t guarantee that users will have JavaScript enabled.)
Yes, it's working:
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
you have to keep first option blank.
You can use the selected attribute for the option element to select a choice by default. You can use the required attribute for the select element to ensure that the user selects something.
In Javascript, you can check the selectedIndex property to get the index of the selected option, or you can check the value property to get the value of the selected option.
According to the HTML5 spec, selectedIndex "returns the index of the first selected item, if any, or −1 if there is no selected item. And value "returns the value of the first selected item, if any, or the empty string if there is no selected item." So if selectedIndex = -1, then you know they haven't selected anything.
<button type="button" onclick="displaySelection()">What did I pick?</button>
<script>
function displaySelection()
{
var mySelect = document.getElementById("someSelectElement");
var mySelection = mySelect.selectedIndex;
alert(mySelection);
}
</script>
You need to set the value attribute of option to the empty string:
<select name="status" required>
<option selected disabled value="">what's your status?</option>
<option value="code">coding</option>
<option value="sleep">sleeping</option>
</select>
select will return the value of the selected option to the server when the user presses submit on the form. An empty value is the same as an empty text input -> raising the required message.
w3schools
The value attribute specifies the value to be sent to a server when a form is submitted.
Example
<form action="">
<select required>
<option selected disabled value="">choose</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="green">green</option>
<option value="grey">grey</option>
</select>
<input type="submit">
</form>
try this, this gonna work, I have tried this and this works.
<!DOCTYPE html>
<html>
<body>
<form action="#">
<select required>
<option value="">None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
</body>
</html>
Make the value of first item of selection box to blank.
So when every you post the FORM you get blank value and using this way you would know that user hasn't selected anything from dropdown.
<select name="user_role" required>
<option value="">-Select-</option>
<option value="User">User</option>
<option value="Admin">Admin</option>
</select>
first you have to assign blank value in first option.
i.e. Select here.than only required will work.
Works perfectly fine if the first option's value is null. Explanation : The HTML5 will read a null value on button submit. If not null (value attribute), the selected value is assumed not to be null hence the validation would have worked i.e by checking if there's been data in the option tag. Therefore it will not produce the validation method. However, i guess the other side becomes clear, if the value attribute is set to null ie (value = "" ), HTML5 will detect an empty value on the first or rather the default selected option thus giving out the validation message. Thanks for asking. Happy to help. Glad to know if i did.
In html5 you can do using the full expression:
<select required="required">
I don't know why the short expression doesn't work, but try this one.
It will solve.
Try this
<select>
<option value="" style="display:none">Please select</option>
<option value="one">One</option>
</select>
You can do it also dynamically with JQuery
Set required
$("#select1").attr('required', 'required');
Remove required
$("#select1").removeAttr('required');

Populating secondary dropdown from main dropdown through JS

I have a dropdown which must populate several other dropdowns depending on the option selected. I found a way how to do this using hidden fields. I created a hidden field for every sub dropdown with all its options. Then from my JS function, I check which selectedIndex is selected and then give the value of its respective hidden field.
This way works great, however, I am setting the value of the sub dropdown using the variable ID FROM the Js function. This reduces flexibility.
Does anybody know any other way how to pass all the parameters from the HTML?
Best method would be that all dropdowns are there but are not displayed. Upon change of the main dropdown, the respective sub drop down ONLY is shown.
Any ideas?
You should be able to do just what you want, have all the dropdowns hidden except the correct one.
<script type="text/javascript">
function changedropdown(index) {
dropdowns['dropdown1'].style.display='none';
dropdowns['dropdown2'].style.display='none';
dropdowns['dropdown3'].style.display='none';
dropdowns['dropdown4'].style.display='none';
dropdowns[index].style.display='inline';
}
</script>
<form name='dropdowns'>
<select onchange='changedropdown(options[selectedIndex].value)'>
<option selected value='dropdown1'>1</option>
<option value='dropdown2'>2</option>
<option value='dropdown3'>3</option>
<option value='dropdown4'>4</option>
</select>
<select name='dropdown1'>
<option selected value=1>dropdown1</option>
</select>
<select style='display:none' name='dropdown2'>
<option selected value=1>dropdown2</option>
</select>
<select style='display:none' name='dropdown3'>
<option selected value=1>dropdown3</option>
</select>
<select style='display:none' name='dropdown4'>
<option selected value=1>dropdown4</option>
</select>
</form>
If I understand the issue, the hidden values are not being returned in your post? To get around this issue I run a routine on submit that grabs all the hidden values and puts them into non hidden inputs of type hidden.
So...assuming you use jquery that would be something along the lines of
<div id='hiddenValues'></div>
<script type='text/javascript'>
function onSubmit() {
var hiddenValue = $('$yourHiddenSelectBox').val();
$('#hiddenValues').append("<input type='hidden' name='someId' value='" + hiddenValue + "'>";
}
</script>

Categories

Resources