Jquery focus not working / scrolling - javascript

I m using the following jquery script to pick a span having a class and focus it
<script type="text/javascript">
$(document).ready(function () {
$('span').each(function () {
if ($(this).hasClass('field-validation-error')) {
$(this).focus();
$(this).addClass('hello');
}
});
});
</script>
For some reasons the focus won't scroll to the span with the class 'field-validation-error' though it does add the class hello to the element.
The section of the html where this span element reside is as belwo
<section id="orderreason">
<div class="orderrow backgrounddot">
<ul>
<li class="widenormal">Please tell us the purpose of your request <span class="asterick">*</span><br>
(this information is used for statistical purposes only)</li>
</ul>
<br>
<p>Please tick any that apply:</p>
<div class="checkboxrow">
<input type="checkbox" value="1" name="orderreason"><label>Patient care</label>
</div>
<div class="checkboxrow">
<input type="checkbox" value="2" name="orderreason"><label>Health improvement</label>
</div>
<div class="checkboxrow">
<input type="checkbox" value="3" name="orderreason"><label>Professional development</label>
</div>
<div class="checkboxrow">
<input type="checkbox" value="4" name="orderreason"><label>Personal development</label>
</div>
<div class="checkboxrow">
<input type="checkbox" value="5" name="orderreason"><label>Management/service improvement</label>
</div>
<div class="checkboxrow">
<input type="checkbox" value="6" name="orderreason"><label>Research</label>
</div>
<p>Other:</p>
<span data-valmsg-replace="true" data-valmsg-for="orderreason" class="field-validation-error">Please choose a reason or enter other text</span>
</div>
</section>

You can focus on non-input elements if you give your HTML a tabindex attribute like so:
<span tabindex="-1"></span>
The -1 value makes it so that the element can't be tabbed by the user, but you can programmatically focus it with el.focus()
Aside
In your implementation, I assume you are creating validation errors. If the validation error occurs next to the input field, why not focus the input field instead of the span? This will have the added benefit of putting the user's cursor where it needs to be to fix the validation issue and deliver an overall better UX.

Related

On click check the closest radio button within div

I am trying to style some radio buttons so that when you click the div, it selects the radio button inside the div.
At the moment, when you click the third div in the list for example, it selects the first div's input. These all have the same ID as it's been written in a razor foreach loop.
here is the HTML generated
<div id="world-container" class="d-flex">
<div class="button-styles image-item">
<input class="city-type-radio" id="CityTypeId" name="CityTypeId" type="radio" value="1">
<label for="CityTypeId">Urban</label>
</div>
<div class="button-styles image-item">
<input class="city-type-radio" id="CityTypeId" name="CityTypeId" type="radio" value="2">
<label for="CityTypeId">Countryside</label>
</div>
<div class="button-styles image-item">
<input class="city-type-radio" id="CityTypeId" name="CityTypeId" type="radio" value="3">
<label for="CityTypeId">Coastal</label>
</div>
</div>
This is the jquery I'm trying to use to select the closest radio button inside that div
$(".button-styles").on("click", function () {
$(this).children('#CityTypeId').prop('checked', true);
});
I can't change the way this HTML is written due to the MVC foreach loop.
Any suggestions or advice how to get around this would be great.
Many thanks in advance
An id should be unique throw a document , you did semantic error by duplicating ids ,
for your issue use classes instead : ( you've already predifined class )
$(this).find('input.city-type-radio').prop('checked', true);
See snippet below :
$(".button-styles").on("click", function () {
$(this).find('input.city-type-radio').prop('checked', true);
});
.image-item {
border:1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="world-container" class="d-flex">
<div class="button-styles image-item">
<input class="city-type-radio" id="cityTypeId1" name="CityTypeId" type="radio" value="1">
<label for="cityTypeId1">Urban</label>
</div>
<div class="button-styles image-item">
<input class="city-type-radio" id="cityTypeId2" name="CityTypeId" type="radio" value="2">
<label for="cityTypeId2">Countryside</label>
</div>
<div class="button-styles image-item">
<input class="city-type-radio" id="cityTypeId3" name="CityTypeId" type="radio" value="3">
<label for="cityTypeId3">Coastal</label>
</div>
</div>
$(this).find('input').prop('checked', true);
ID has to be unique, that's the reason why your code don't work. Try to target input directly.
$(this).children('input').prop('checked', true);

Using jquery to enable div on a page based on a radio button selection

I want to be able to enable a div if yes or no was selected from a radio button using jquery. The default is no div shows up
when the page loads. When you now select a radio button it determines which div shows up.
Here is what the html code will look like
<html>
<head>Testing</head>
<body>
<p>Are you 70 years and older? <input type="radio" value="yes" name="myradiobutton" /> Yes <input type="radio" value="no" name="myradiobutton" /> No</p>
<div style="display: none" id="yes">
<p>Yes was selected</p>
</div>
<div style="display: none" id="no">
<p>No was selected</p>
</div>
</body>
</html>
It is a long time I did jquery but was wondering how I can turn this on and off with jquery below.
How can I write this such that I will be able to control the styles on each div via jquery(turning it on and off based on the radio button selection)?
$(".myradiobutton").click(function(){
var selectedval = $("#myradiobutton input[type='radio']:checked").val();
if(selectedval == "yes"){
//show the yes div
}
if(selectedval == "no"){
//show the no div
}
});
Id must be unique .. You've to use it for only one element .. You can use same class for divs so you can hide both of them in one selection .. Also you can use the code like this instead of going with if statement .. And I prefer to use change event instead of click for radio,checkbox,select
$("[name='myradiobutton']").on('change' , function(){
var selectedval = $("input[type='radio'][name='myradiobutton']:checked").val();
$('.just_test').hide(0).filter('#'+selectedval).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Are you 70 years and older? <input type="radio" value="yes" name="myradiobutton" /> Yes <input type="radio" value="no" name="myradiobutton" /> No</p>
<div style="display: none" class="just_test" id="yes">
<p>Yes was selected</p>
</div>
<div style="display: none" class="just_test" id="no">
<p>No was selected</p>
</div>
Don't forget to add class="just_test" to the divs in html
You tried to use #myradiobutton as a query selector but the # represents the id attribute of an element which you don't have in your HTML code.
To fix it, you can't have your two <input type="radio"> elements both using the myradiobutton as id.
Instead of that, my suggestion is to use <label> to represent the <input>s.
Example below:
<input type="radio" name="age" value="yes" id="older-than-70">
<label for="older-than-70">Yes</label>
<input type="radio" name="age" value="no" id="younger-than-70">
<label for="younger-than-70">No</label>
<input> element uses attribute id to identify itself and uses attribute name="age" to group with other <input>s.
<label> element uses attribute for as a pointer to hook to the <input> with matching id.

How to add html element around another html element using jquery

Another day, another problem. I have something like that:
<p class="checkbox">
<input name="cgv" id="cgv" value="1" type="checkbox">
<label for="cgv">Some text.</label>
</p>
Using jquery I want to change this code to:
<p class="checkbox">
<div class="checker" id="uniform-cgv">
<span>
<input name="cgv" id="cgv" value="1" type="checkbox">
</span>
</div>
<label for="cgv">Some text.</label>
</p>
So, the input element #cgv is inside span and div elements. I want to do this by this code but without any results.
$('#submitGuestAccount').click(function () {
//True if parent is <p> element
if ($('#cgv').parent().hasClass('checkbox')) {
$('<span>').insertBefor('#cgv');
$('</span>').insertAfter('#cgv');
}
});
Is anyone can help me with my problem ?
Kind regards
The jQuery API is well documented : http://api.jquery.com/wrap/.
$("#cgv").wrap(
"<div class=\"checker\" id=\"uniform-cgv\"><span></span></div>"
);
div{border:10px solid red}
span{border:10px solid blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="checkbox">
<input name="cgv" id="cgv" value="1" type="checkbox">
<label for="cgv">Some text.</label>
</p>

If check box is cheked show/hide div (by searching trough object property)

I'm making one web site, and I'm stuck. I have 6 checkboxes:
<div class="checkbox">
<label>
<input type="checkbox" value="Pizza" id="pizza">
Pizza
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="BBQ" id="bbq">
BBQ
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="Chicken" id="chicken">
Chicken
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="Pasta" id="pasta">
Pasta
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="Chinese" id="chinese">
Chinese
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="Mexican" id="mexican">
Mexican
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="Indian" id="indian">
Indian
</label>
</div>
</div>
<div class="col-xs-7">
<div class = "restaurant" id="Paradiso">
</div>
</div>
<div class="col-xs-7">
<div class = "restaurant" id="Wingsy">
</div>
</div>
And a lot more of restaurant class div's.
So, I want to make: when checkbox are cheked they search trough restaurants and if that restourant have property that is in checkbox, it shows. Otherwise it hides.
Example:
var typeOfKitchen = ['pizza','bbq','chicken','pasta','chinese','mexican','indian'];
var restaurants = new Array();
restaurant = new Object();
restaurant.[name] = "Paradiso";
restaurant.[type] = typeOfKitchen[0];
restaurants.push(restaurant);
restaurant = new Object();
restaurant.[name] = "Wingsy";
restaurant.[type] = typeOfKitchen[2];
restaurants.push(restaurant);
And then I'm stuck with code to take value of checkbox and search trough restaurants and shows only restaurants who have that property, and hide others that dont have.
Firstly, it is good practise to use jsFiddle to show your code.
Look this fiddle: http://jsfiddle.net/EtJ6L/5/
I had restructured your code a bit, added some css and js.
New HTML code:
<div class="checkbox">
<input type="checkbox" value="Pizza" id="pizza" />
<label>Pizza</label>
</div>
<div class="checkbox">
<input type="checkbox" value="BBQ" id="bbq" />
<label>BBQ</label>
</div>
<div class="checkbox">
<input type="checkbox" value="Chicken" id="chicken" />
<label>Chicken</label>
</div>
<div class="checkbox">
<input type="checkbox" value="Pasta" id="pasta" />
<label>Pasta</label>
</div>
<div class="checkbox">
<input type="checkbox" value="Chinese" id="chinese" />
<label>Chinese</label>
</div>
<div class="checkbox">
<input type="checkbox" value="Mexican" id="mexican" />
<label>Mexican</label>
</div>
<div class="checkbox">
<input type="checkbox" value="Indian" id="indian" />
<label>Indian</label>
</div>
<div class="col-xs-7">
<div class="restaurant" id="pizza">Paradiso</div>
</div>
<div class="col-xs-7">
<div class="restaurant" id="bbq">Wingsy</div>
</div>
Added CSS:
.restaurant {
display: none;
}
Added jQuery:
$(":checkbox").change(function () {
var id = $(this).attr('id');
$(".restaurant#" + id).toggle(this.checked);
});
How it works?
Notice, that I changed block with info about restraunts. Now name of restraunt (and other info will be there too) is inner html of div. Also, to achieve what you want you have to connect restraunt blocks with inputs.
Look this block html, for example:
<div class="col-xs-7">
<div class="restaurant" id="bbq">Wingsy</div>
</div>
Firstly, name is inner hmtl. Also, I added type of restraunt into id attribute of this div.
Look this input html (connected with restraunt):
<div class="checkbox">
<input type="checkbox" value="BBQ" id="bbq" />
<label>BBQ</label>
</div>
Firstly, I restrucutred it a bit. Now it is more valid, than was. Also, notice id attribute of this input. So input and divs are connected now.
Divs with restraunt's info are hidden from start. It is achieved by css code display: none.
Now take a look on jQuery code.
$(":checkbox").change(function () {
var id = $(this).attr('id');
$(".restaurant#" + id).toggle(this.checked);
});
We handling change action on all checkbox elements on page. We save id of checkbox was clicked on. After that we toggle .restraunt#xxx element, where xxx is id of this element. Div's and input's are connected, so this approach will work. Toggle displays or hide element. Read here about it.
Hope this will help you.
Note I think better approach is to make ajax request to the server depending on checkbox checked, then cache and output ajax response.
If you have situation, that restraunt can have more then 1 kitchen As I said earlier better way is to use ajax request. You will send some parameters like bbq=true&pizza=true, server will handle this query and will return some response, depending on query. I had written an example for you. Look this fiddle: http://jsfiddle.net/EtJ6L/8/.
On checkbox click ajax request sending to script bob.php, for example. Look, what data is sending with it. On bob.php you will handle this query. Something like $pizza = $_POST['pizza']; if($pizza != "") { // add something to sql query } etc.

Checked Another hidden radio Button

hello,
I'm trying to select hidden radio input when selecting another one
<div class="questions">
<div class="questions_title">
<span> Q : What Are you doing now ?</span>
</div>
<div class="answers">
<script>
$('#answerid_').on('checked', function() {
$('#degres_').prop('checked', true);
return false;
});
</script>
<div class="field">
<input type="radio" value="1915" id="answerid_1" name="answerid_1" class="required">
<input type="hidden" value="0" id="degres_1" name="degres_1">
<span class="questions_label">Working. </span>
</div>
<div class="field">
<input type="radio" value="1916" id="answerid_2" name="answerid_1">
<input type="hidden" value="1" id="degres_2" name="degres_1">
<span class="questions_label">Playing.</span>
</div>
<div class="field">
<input type="radio" value="1917" id="answerid_3" name="answerid_1">
<input type="hidden" value="2" id="degres_3" name="degres_1">
<span class="questions_label">not Sleeping </span>
</div>
<div class="field">
<input type="radio" value="1918" id="answerid_4" name="answerid_1">
<input type="hidden" value="3" id="degres_4" name="degres_1">
<span class="questions_label">Nothing.</span>
</div>
</div>
I need => When selecting any answer the according next hidden degree would be checked too
You can't check a hidden-type input. However, you can check a radio-type invisible input (with display:none style).
it should be..
$('[id^=answerid_]').on('change', function() {
$(this).next().prop('checked', true);
return false;
});
You need wild card to attach event and change event.
Live Demo
$('[id^=answerid_]').on('change', function() {
$(this).next(':hidden').prop('checked', true);
return false;
});
Instead of using check of hidden I would suggest you to set the value of hidden field.
$(this).next(':hidden').val("true");
you can try this
JS CODE
$('[id^=answerid_]').on('change', function() {
$(this).siblings('[id^=degres_]').prop('checked', true);
alert($(this).siblings('[id^=degres_]').prop('checked'));
return false;
});
DEMO
You can't check a hidden-type input. it is expecting a value, so the value could be 1 if previous is cecked or 0 if not checked.
after use the folowing code
$('[id^=answerid_]').on('change', function() { $(this).siblings('[id^=degres_]').prop('checked', true); //alert($(this).siblings('[id^=degres_]').prop('checked')); return false; });
and changing hidden input to another radio because it now work and by adding
style="margin-left: -16px; position: absolute;"
for every answer input to be above degrees radio it work successfully.
but in the last question it's not work or check degree input :(

Categories