This question already has answers here:
How to set HTML5 required attribute in Javascript?
(6 answers)
Closed 5 years ago.
the required in the script do not working
$("#s_postby").attr('required', false); // put the id of the input field that you whant required
$("#s_postby").attr('required', true); // put the id of the input field that you whant required
I make some radio field in my osclass theme on the item post!
<div id="postby" class="property-ads-100">
<label>
<span class="required_fields">*</span>
<?php _e('Posted By', 'ctg_housing'); ?>
</label>
<div class="item-post-postby-checkbox columns-0">
<input type="radio" name="s_postby" value="owner" id="s_postby0" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='owner') { echo 'checked="checked"'; }; ?>>
<label for="s_postby0">
<?php _e('Owner', 'ctg_housing'); ?>
</label>
</div>
<div class="item-post-postby-checkbox columns-0">
<input type="radio" name="s_postby" value="agent" id="s_postby1" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='agent') { echo 'checked="checked"'; }; ?>>
<label for="s_postby1">
<?php _e('Agent', 'ctg_housing'); ?>
</label>
</div>
<div class="item-post-postby-checkbox columns-0">
<input type="radio" name="s_postby" value="broker" id="s_postby2" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='broker') { echo 'checked="checked"'; }; ?>>
<label for="s_postby2">
<?php _e('Broker', 'ctg_housing'); ?>
</label>
</div>
<div class="item-post-postby-checkbox columns-0">
<input type="radio" name="s_postby" value="agency" id="s_postby3" <?php if(isset($housing['s_postby']) && $housing['s_postby'] =='agency') { echo 'checked="checked"'; }; ?>>
<label for="s_postby3">
<?php _e('Agency', 'ctg_housing'); ?>
</label>
</div>
</div>
I hide this on some categories (the required in the script do not work!!) Why??
<script type="text/javascript">
$('#catId').change(function(){
if( $('#catId').val() == "28" || $('#catId').val() == "29" ||
$('#catId').val() == "30" || $('#catId').val() == "31")
{
$("#postby").hide(); // change Posted By with ID you give to the div
$("#s_postby").attr('required', false); // put the id of the input field that you whant required
}else
{
$("#postby").show(); // change Posted By with ID you give to the div
$("#s_postby").attr('required', true); // put the id of the input field that you whant required
}
});
</script>
What i need now it to make this radio fields required when show and not required wen hide! When show and required i need a error message Posted By: This field is required!
Hope someone can help me!
element.required = true;
How to set HTML5 required attribute in Javascript?
Related
I would like to hide/show || disable/enable an input field based on the selected country in magento checkout page. I tried this code separated from magento and it's working perfectly but when I applied it in my magento, it's not working. I just edited the billing.phtml from IWD checkout extension and nothing from magento core.
here is the javascript:
$(function() {
var $cid = $(document.getElementById("billing:country_id")), // Country ID in magento
$custom = $(document.getElementById("billing:custom")); //my custom input field
$cid.change(function() {
if ($cid.val() == 'US') {
$custom.removeAttr('disabled');
alert('working1');
} else {
$custom.attr('disabled', 'disabled').val('');
alert('working2');
}
}).trigger('change');
});
Here's the sample billing form template from IWD / Magento:
<li class="fields">
<label for="billing:country_id" class="required"><em>*</em><?php echo $this->__('Country') ?></label>
<div class="input-box">
<?php echo $this->getCountryHtmlSelect('billing') ?>
</div>
</li>
<li class="fields">
<label for="billing:custom" class="required"><em>*</em><?php echo $this->__('Custom Field') ?></label>
<div class="input-box">
<input type="text" name="custom[custom]" value="<?php echo $this->htmlEscape($this->getQuote()->getCustom()) ?>" title="<?php echo $this->__('Custom Field') ?>" class="input-text custom_id" id="billing:custom" />
</div>
</li>
Country Select getCountryHtmlSelect function is a built-in mage function:
public function getCountryHtmlSelect($type)
{
$countryId = $this->getAddress()->getCountryId();
if (is_null($countryId)) {
$countryId = Mage::helper('core')->getDefaultCountry();
}
$select = $this->getLayout()->createBlock('core/html_select')
->setName($type.'[country_id]')
->setId($type.':country_id')
->setTitle(Mage::helper('checkout')->__('Country'))
->setClass('validate-select')
->setValue($countryId)
->setOptions($this->getCountryOptions());
if ($type === 'shipping') {
$select->setExtraParams('onchange="if(window.shipping)shipping.setSameAsBilling(false);"');
}
return $select->getHtml();
}
<input id="billing:country_id"></input>
<input id="billing:custom" disabled="disabled;"></input>
code
$(function() {
var $cid = $(document.getElementById("billing:country_id"));
$custom = $(document.getElementById("billing:custom"));
$cid.change(function() {
if ($cid.val() == 'US') {
$custom.prop('disabled', false);
console.log('working1');
} else {
$custom.prop('disabled', true).val("");
console.log('working2');
}
}).trigger('change');
});
http://codepen.io/anon/pen/dMqYgK?editors=1011
I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name
I have 3 check-boxes where I can submit them into MySQL. It inserts perfectly, but the problem is, is when I go back to to edit the game, the check-boxes are not checked at all with their correct values (they are empty).
I know there are a lot of answers on this website about this problem, but I found none of them to work. Maybe its something that Im doing wrong with the code. I will post it here.
THIS IS THE SHORT VERSION OF MY CODE, BECAUSE ITS TOO BIG.
if (isset($_GET['add']) || isset($_GET['edit'])) {
$checkbox = ((isset($_POST['available_consoles']) && $_POST['available_consoles'] != '') ? sanitize($_POST['available_consoles']) : '');
if (isset($_GET['edit'])) {
$checkbox = ((isset($_POST['available_consoles']) && $_POST['available_consoles'] != '') ? $_POST['available_consoles'] : $game['available_consoles']);
}
if ($_POST) {
// Separate ech checkbox value with a SPACE into the database.
$checkbox = implode(', ', $_POST['available_consoles']);
// DO INSERT HERE
}
}
<!-- Add the Add Form -->
<form action="games.php?<?php echo ((isset($_GET['edit'])) ? 'edit='.$edit_id : 'add=1'); ?>" method="post" enctype="multipart/form-data">
<!-------------- AVAILABLE CONSOLES ------------------->
<div class="form-group col-md-6">
<label for="checkbox">Available Consoles: </label>
<label class="checkbox">
<input type="checkbox" <?php if (in_array('Xbox One', $_POST['available_consoles'])) {echo 'checked';} ?> name="available_consoles[]" value="Xbox One">
</label>
<label class="checkbox">
<input type="checkbox" <?php if (in_array('PS4', $_POST['available_consoles'])) {echo 'checked';} ?> name="available_consoles[]" value="PS4">
</label>
<label class="checkbox">
<input type="checkbox" <?php if (in_array('PC', $_POST['available_consoles'])) {echo 'checked';} ?> name="available_consoles[]" value="PC">
</label>
</div>
<div class="form-group pull-right">
Cancel
<input type="submit" value="<?php echo ((isset($_GET['edit'])) ? 'Edit ' : 'Add '); ?> Game" class="btn btn-success">
</div>
</form>
Getting these error message next to checkbox:
Notice: Undefined index: available_consoles in C:\xampp\htdocs\Gamesite\admin\games.php on line 425
Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\Gamesite\admin\games.php on line 425
name="available_consoles[]" value="Xbox One">
Getting it for all 3 checkboxes
this is what you need
<input type="checkbox" <?php if (in_array('Xbox One', $_POST['available_consoles'])) {echo 'checked';} ?>id="checkbox" name="available_consoles[]" value="Xbox One">
replace in_array('Xbox One'
with the other consoles names for each input
Here is simple function:
function checked($t,$v){
if (in_array("{$t}", $v)) {
return 'checked';
}
}
use : <?php echo checked('Xbox One',$con); ?>
it was not an array nor was it from $_POST it was actually from the DB so i appended my code to match the answer.
My code looks like this:
form action="familytree.php" method="post">
<?php
foreach ($spouses as $spouse) {
if (!empty($spouse['mname'])) {
$name = $spouse['fname'].' '.$spouse['lname'].' ('.$spouse['mname'].')';
}
else {
$name = $spouse['fname'].' '.$spouse['lname'];
}
if ($spouse['ended'] == '1') {
$married = '';
$divorced = 'checked';
}
else {
$married = 'checked';
$divorced = '';
}
?>
<div class="form_section dates">
<h3><?php echo $name; ?></h3>
<p>
<input type="radio" id="married_option" name="married_divorced_options" <?php echo $married; ?> value="1"/>
<label for="edate">Married</label>
<input type="radio" id="divorced_option" name="married_divorced_options" <?php echo $divorced; ?> value="1"/>
<label for="sdate">Divorced</label>
</p>
<div class="half" style="display: inline">
<input type="text" name="sdate_<?php echo $spouse['individual_id']?>" id="sdate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['start_date']; ?>" placeholder="Rašykite sutuoktuvių datą čia"/>
<?php echo $this->formError->error("sdate_".$spouse['individual_id'].""); ?>
</div>
<div id="divorced" class="half" style="display:none">
<input type="text" name="edate_<?php echo $spouse['individual_id']?>" id="edate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['end_date']; ?>" placeholder="Rašykite skyrybų datą čia"/>
<?php echo $this->formError->error("edate_".$spouse['individual_id'].""); ?>
</div>
</div>
<?php
}
?>
<p class="submit">
<input class="first-btn" type="submit" id="edit-relationship" name="edit-relationship" value="Edit"/>
</p>
</form>
jQuery("#divorced_option").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("#married_option").click(function() {
document.getElementById("divorced").style.display = "none";
});
What I would like to know is how to check if a radio button is clicked when you don't know its full name, only half of it. For example, #divorced_option is not full name, it should be something like this #divorced_option_161, #divorced_option_161... So, the code should check if the radio button that has divorced_option in its name is clicked. Is there a way to achieve this?
EDIT
It works with jQuery("[id^='married_option']").click(function(){}). But I forgot to mention in my original question that the element divorced isn't full name as well, it should be divorced_161, divorced_162, depending of the name of the radio button that is clicked. How can I hide the element that matches with the radio button?
Use the attribute starts with selector (ex. [name^="value"]):
jQuery("[id^='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id^='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
Have a look at the jQuery selectors.
The 'Attribute Contains' selector would be useful here, which means your code would be :
jQuery("[id*='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id*='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
You can select the elements based on the #divorced_option_[number] pattern while checking if they are selected like this:
$("input[id*=divorced_option]:checked");
If you would like to check wether the divorced_option substring is in the name="" attribute of the radio element, then change the id from the selector to name, like so:
$("input[name*=divorced_option]:checked");
After this, just check wether or not jQuery returned an actual element.
I have used the code below elsewhere in my site and it works. For the life of me I can't understand why it doesn't work here. PROBLEM: keeps throwing alert message.
My HTML:
<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
<div class="outerBlue" style="background:white">
<button type="button" id="cancelForm" class="button" title="Cancel">X</button>
<br><br>
<h3>Get involved—join a committee!</h3>
<?php if(empty($name)||empty($email)||empty($workPhone)){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
<label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
<label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
<label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
<hr>
<p class="clear">Please select a committee from the list below</p><br><br>
<select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
<option value="">Select one...</option>
<?php
$sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
}
echo "</select>";?>
<input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
<div class="clear"></div>
<p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
</div>
</form>
My JS:
$("#joinCommitteeForm").submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
alert('All fields are required');
return false;
}
});
What I suspect the problem is here, is that you are testing if $name or $email is empty, but since you never define them, they will always be empty, per PHP empty() docs: "A variable is considered empty if it does not exist or if its value equals FALSE".
To fix that, you'll need to change your PHP if-statement to:
<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
Also, your POST parameter $workPhone doesn't seem to exist in your form. I've changed it to dayPhone here.
The variable $_POST will contain all parameters in the POST request from the form that's submitted.