Javascript: Checked radio button - javascript

In one page I have two form for search:
<form class="search-panel" method="post" action="" onsubmit="return searchRedirect(this)">
<input type="test" name="searchFor" />
<div class="additional-search-button"></div>
<div id="additional-search-box">
<div class="as-cont">
Books<input type="radio" name="category" value="Books" checked="1" /><br/>
School<input type="radio" name="category" value="School" /><br/>
Music<input type="radio" name="category" value="Music" />
</div>
</div>
<input type="submit" name="search" />
</form>
<form class="search-panel" method="post" action="" onsubmit="return searchRedirect(this)">
<input type="test" name="searchFor" />
Games<input type="radio" name="category" value="Games" checked="1" />
<input type="submit" name="search" />
</form>
My problem is that if I click search for Games in searchRedirect always alert Books, School or Music if they checked:
That is my javascript function:
function searchRedirect(form) {
alert($(form['category']+':checked').val());
if($(form['category']+':checked').val() == 'Форум')
window.location.href = '/forum/search.php?keywords='+form['searchFor'].value;
else {
window.location.href = '/Search/'+$(form['category']+':checked').val()+'/'+form['searchFor'].value;
}
return false;
}
I need if I click to search games - search only for games, if click to search books,school or music - searching only for them. But now search form for games always use first form checked buttons.

form['category'] will give you a NodeList of all form elements whose name is category, thus you can't use it as a selector by concatenating it with :checked. It'd be the equivalent of $("[object NodeList]:checked").
Since you are already using jQuery, you can use the following instead:
alert($(form).find("input[name='category']:checked").val());
That is, within the context of form, find every input element with name category that is checked, and get its value.

you can't real do form["category"] + ":checked", instead use jQuery's filter method and than use 'this' to reference the form. Also, you can/should use jQuery .submit() to catch the event instead of an inline handler and just for clearer code (and also for better performance) put the $(form['category']+':checked') into a variable so jquery won't need to search for the element again and again.
This is a sample:
$('form').submit(function(e){
var checked = $(this['category']).filter(':checked');
var value = checked.val();
alert(value);
})​
This is a fiddle so you can fiddle (the e passed to the submit callback is the event object and e.preventDefault is like returning false so the form won't submit):
http://jsfiddle.net/SJ7Vd/

Related

Associate a checkbox with an input field and make it mandatory only if input value exists

I am trying to make a manual verification system and want the user to check each checkbox associated with individual inputs if a value exists before submission else the form would throw an error.
I have implemented this, but it does not seem to work. Also, I was wondering if there was a better way of achieving the same wherein we avoid passing the parameters to the function.
Similar to how we can associate a submit button for a form using form by supplying the id.
<form>
<input type="text" name="inputFieldOne">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
<script>
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
if(fieldBox.value != ''){
checkBox = document.getElementsByName(checkbox)[0];
checkBox.required = true;
}
}
</script>
If you want to set the checkbox to be required when the field has a value, you should hook an event on the field, not the checkbox. input would make a good event for this:
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
let checkBox = document.getElementsByName(checkbox)[0];
// Require the checkbox when the field has a value
checkBox.required = fieldBox.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
Note that there's no need for those calls to getElementsByName: Just pass this into the function, and use nextElementSibling to access the checkbox:
function makeSureItIsSelected(field){
// Require the checkbox when the field has a value
field.nextElementSibling.required = field.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
That said, it seems odd to have the checkboxes at all. The presence of the field in the form data should be sufficient. But if the checkbox's value has to be in the form data, simply add it on submit without having a checkbox at all.

Clear textbox and radio buttons onclick with Javascript

<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text" value="" />
So basically, this is my html. What I want to do now, is to use JavaScript, not jQuery, to clear the text input field (if something had previously been entered) whenever the radio buttons are clicked and to uncheck the radio buttons whenever someone clicks onto the text field. I quickly found a jQuery solution, but got the task to use JavaScript instead. As I'm not having very much experience with JS, I can't wrap my head around it to get it to work.
Any thoughts?
Would appreciate very much.
You can use .querySelectorAll() and .querySelector() in order to find the elemnts and .addEventListener() to attach the event handlers:
document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.addEventListener('change', function(e) {
document.querySelector('#locationName').value = '';
});
});
document.querySelector('#locationName').addEventListener('input', function(e) {
document.querySelectorAll('#firstLocation, #secondLocation').forEach(function(ele, idx) {
ele.checked=false;
});
})
<input id="firstLocation" type="radio" />
<label for="firstLocation">text</label>
<input id="secondLocation" type="radio" />
<label for="secondLocation">text</label>
<input class="cityName" id="locationName" type="text" value="" />

Using isset from a name of an input

I am not sure if I am going about this correctly. I have a set of checkbox inputs. If someone selects the last check box all_users_check, I want a new form to appear where I will be listing all of the users in a drop down (haven't added the drop down yet). I thought I could do this by using the name of the input, but I am mistaken apparently as I am getting this error..
How else could I structure what I am doing so that if someone checks that option the new form displays?
<div class="user_dropdown">
<form action="">
<input type="checkbox" name="spectator_check" value=""> Spectators<br>
<input type="checkbox" name="member_check" value="" checked> Team Members<br>
<input type="checkbox" name="commissioner_check" value="" checked> Commissioner(s)<br>
<label for="all_users_check">
<input type="checkbox" name="all_users_check" value="" checked> Individual User<br>
</label>
</form>
</div>
<script>
$(".user_dropdown").hide();
$(".all_users_check").click(function() {
if($(this).is(":checked")) {
$(".user_dropdown").show();
} else {
$(".user_dropdown").hide();
}
});
</script>
This is how the page looks on load. Those fields are already checked for some reason.
Issues in your code.
.all_users_check that is looking for a class. Your element doesn't have a class so this isn't found. You can use a different selector to use the name attribute, https://api.jquery.com/attribute-equals-selector/.
This $(".user_dropdown").hide(); hides your whole form. You might want to move around your divs, or remove that altogether.
The checked attribute checks the field it is on. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
Use the checked attribute to indicate whether this item is selected
<div class="user_dropdown">
<form>
<input type="checkbox" name="spectator_check" value=""> Spectators<br>
<input type="checkbox" name="member_check" value=""> Team Members<br>
<input type="checkbox" name="commissioner_check" value=""> Commissioner(s)<br>
<label for="all_users_check">
<input type="checkbox" name="all_users_check" value=""> Individual User<br>
</label>
</form>
</div>
<script>
//$(".user_dropdown").hide();
$("input[name='all_users_check']").click(function() {
if($(this).is(":checked")) {
$(".user_dropdown").show();
} else {
$(".user_dropdown").hide();
}
});
</script>
isset is a language construct and can't accept anything other than a variable as indicated by this warning on the linked to manual page:
Warning isset() only works with variables as passing anything else will result in a parse error.
You are not passing in a variable to the isset function, you are passing in a constant value, basically an array with a single string all_users_check. This is not a variable because you are not assigning it to a variable name. Try this instead:
if(isset($_POST['all_users_check']))
Here the variable being passed in is the superglobal $_POST, and you are checking to see if the index all_users_check is set inside of that array.
Update
To check if an input is empty or not via javascript, take a look at this question.
Try using this script, you have set the state of check boxes as checked by default.
<div class="user_dropdown">
<form action="">
<input type="checkbox" name="spectator_check" value=""> Spectators<br>
<input type="checkbox" name="member_check" value=""> Team Members<br><!-- removed 'checked' from this line -->
<input type="checkbox" name="commissioner_check" value=""> Commissioner(s)<br><!-- removed 'checked' from this line -->
<label for="all_users_check">
<input type="checkbox" name="all_users_check" value="" > Individual User<br> <!-- removed 'checked' from this line -->
</label>
</form>
</div>
<script>
$(".user_dropdown").hide();
$(".all_users_check").click(function() {
if($(this).is(":checked")) {
$(".user_dropdown").show();
} else {
$(".user_dropdown").hide();
}
});
</script>
For the other issue of showing the hidden section again, try whether class all_users_check is visible to click.

Input Tags and Submit form outside the <form>

I know how to submit a form from outside the form, for example:
<form action="Get?id_sec=120" method="post" id="form15" name="form15" style="display:none"></form>
<input type="submit" class="finish-button primary-button button" border="0" value="Limpar pedido" form="form15" onclick="javascript:document.form15.submit();" />
But I want to put a tag with a reference to the form with javascript too, because command form="example" doesn't work in Internet Explorer.
example:
<input class="input-cep" name="pr001" id="cepfrete" type="text" form="form15"/>
or
<input type="radio" name="tipofrete" value="4" form="form15">`
How can I do that?
Hey Vince, thanks, this works. Very useful help! I need just one other thing. How can I put an input and select in the same form in jQuery?
example:
<input type="text" data-form="dataForm" name="external-input-2">
<Select id="selectField_1" name="selectField_1" data-form="dataForm" >
<option value="52" data-form="dataForm">A</option>
</Select>
To submit a form from outside the form:
HTML
<form id="theForm">...</form>
<button id="submitTheForm">Click to Submit</button>
jQuery
$('#submitTheForm').on('click', function() {
$('#theForm').submit();
});
To include external inputs in the form submission:
HTML
<form id="theForm">...</form>
<button id="submitTheForm">Click to Submit</button>
<input type="text" data-form="theForm" name="external-input-1">
<input type="text" data-form="theForm" name="external-input-2">
jQuery
You can append the external inputs as hidden inputs to the form:
$('#submitTheForm').on('click', function() {
var form = $('#theForm');
$('input[data-form="theForm"]').each(function() {
var input = $(this);
var hidden = $('<input type="hidden"></input>');
hidden.attr('name', input.attr('name'));
hidden.val(input.val());
form.append(hidden);
});
form.submit();
});
I'm not sure that I can completely understand your question but if you are asking how to submit a form externally in different situations, her is my answer.
For the future, just put an id on the form like this.
<form id="form15"></form>
Then to submit this form from anywhere, all you have to do is call the following javascript line in an onclick, a function, etc.
document.getElementById("form15").submit();

Disabling a link until a series of checkboxes are checked

I'm trying to figure out how to disable the following link until a series of 4 or 5 checkboxes have been selected.
<input type="image" src="/wp-content/themes/happy/images/add-to-cart.png" name="Buy" class="wpsc_buy_button" id="product_<?php echo wpsc_the_product_id(); ?>_submit_button" onclick="window.location='http://example.com/store/checkout/';"/>
Thanks!
I'm also kind of retarded when it comes to js and jquery, so the simpler the better, please. I would like to have all the code right there near the element, and not off in a different location, even though that might be the "preferred" method.
Thanks a lot.
You can do something like this
<input type="image" src="/wp-content/themes/happy/images/add-to-cart.png" name="Buy" class="wpsc_buy_button" id="product_<?php echo wpsc_the_product_id(); ?>_submit_button" onclick="if($(this).data("enabled")){window.location='http://example.com/store/checkout/';}"/>
And on check box click do this
$("input").click(function(){
//Here check for this checkbox and all other series of checkbox, if they are checked then
$("img[name=Buy]").data("enabled", true);
//else
$("img[name=Buy]").data("enabled", false);
});
Assuming you have jquery referenced, change your onclick method to something like;
onclick="if($('.checkboxClass').not(':checked').length > 0) window.location='http://example.com/store/checkout/'; else {alert('please tick all the checkboxes'); return 0};
Then add the "checkboxClass" (or whatever class you choose) to all of your checkboxes
<input type="checkbox" class="checkboxClass" value="1" />
<input type="checkbox" class="checkboxClass" value="2" />
And so on.
If you have the following form:
<form method="post" action="" class="my-form">
<p>
<input type="checkbox" /> First item
</p>
<p>
<input type="checkbox" /> Second item
</p>
<p>
<input type="image" src="..." />
</p>
</form>
Use jQuery to check on form submit
$(function() {
$(".my-form").submit(function() {
if ($(".my-form input[type=checkbox]:checked").length < 1)
{
alert("You must select at least one checkbox to proceed.");
return false;
}
}
}

Categories