I'm trying to perform a search of database when user enters a persons name into textbox. The texboxes are dynamic, so whenever the user enters a number into the "No. of firemen on scene" textbox as seen in the snap shot below, the same amount of textboxes appear in the fieldset below under("List of firemen on scene").
However, my problem is that whenever I'm trying to perform the search, the search is only performed on the first textbox and not on the others. Could anyone assist me as to highlighting and/or explaining what the problem(s) may be?
occurrence.php
<label>List of Firemen On Scene</label><br>
<div class="NewlyCreatedSelectBoxes" name="firemen_list"></div>
search.php
<?php
require('connectdb.php');
if(isset($_POST['search_term']))
{
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if(!empty($search_term))
{
$search = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName` FROM `firefighterinfo` WHERE `firstName` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<p>Your search for ', $search_term, ' returned ', $result_count, ' result', $suffix, '</p>';
while($results_row = mysql_fetch_assoc($search))
{
echo '<p>', $results_row['firstName'], ' ', $results_row['middleName'], ' ', $results_row['lastName'], '</p>';
}
}
}
?>
search.js
function firemanAddingTextBoxes() {
var NumOfText = $("#NumOfTextBoxes").val();
$('.NewlyCreatedSelectBoxes').empty();
var txtBox = "";
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" id="search" required/><br>';
}
$('.NewlyCreatedSelectBoxes').append(txtBox);
$('#search').keyup(function () {
var search_term = $(this).val();
$('#search_results').html('Searching database...');
if (search_term !== '') {
$.post('php/fireman_search.php', { search_term: search_term }, function (data) {
$('#search_results').html(data);
});
} else {
$('#search_results').html('Not Found');
}
});
return false;
}
Since the other field is dynamic, you'll need to use event delegation on the search inputs. Also, you're adding elements with duplicate ID's, which is bad. ID's have to be unique, just use classes for this:
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" class="search" required/><br>';
}
Change:
$('#search').keyup(function () {
To:
$(".NewlyCreatedSelectBoxes").on("keyup", ".search", function() {
Related
Using the answer provided in this thread (Woocommerce: How to show Product Attribute name on title when in a category page and "filtering" products via '?pa_attribute=' on address bar) I would like to display the category as well as the attribute name. I have a separate JS function that is currently updating the page_title when a filter is applied but that is only loading after ajax has finished. So in this event it would not load till after the filter is applied.
In the event that a user uses the nav to get to the category, currently only the attribute is displaying in the page_title. Looking to also display the category. I believe this would work out of the box if I organized my products in to subcategories but due to how the filtering is being set up I elected not to go this route. I can explain in further detail why I had to take this approach if anyone is interested.
I have left the commented out code in so that you can see the approach I was attempting to take. If this is confusing can edit it out.
add_filter( 'woocommerce_page_title', 'custom_woocommerce_page_title', 15, 2 );
function custom_woocommerce_page_title( $page_title ) {
if ( is_archive() ) {
$exists_attr = false;
foreach ( $_GET as $index => $value ) {
if ( substr( $index, 0, 3 ) === 'pa_' ) {
//$cat_id = wc_category_taxonomy_id_by_name( $index );
$attr_id = wc_attribute_taxonomy_id_by_name( $index );
if ( $attr_id === 0 && $cat_id ) {
continue;
}
if ( ! $exists_attr /* && ! $exists_cat */) {
$exists_attr = true;
//$exists_cat = true;
$page_title .= ' ';
} else {
$page_title .= ' ';
}
//$terms = get_the_terms( $post->ID, 'product_cat' );
$term = get_term_by( 'slug', esc_html( $value ), $index );
$page_title = /*$terms->name . ': ' . */ $term->name;
}
}
}
// Need to add category name after attribute term name.
return $page_title;
}
Also, I have included the JS I am using to apply page_title in the event a filter selection occurs. Ideally it would be great if I could handle it all via a JS file as I am much more familiar with JS and just starting to dive in to php. I am using the WOOF - WooCommerce Products Filter and modifying some of the code to accomplish what I need.
(function() {
var machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
var processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
var optionMachine = machineEl.querySelector("option[selected='selected']");
var optionProcess = processEl.querySelector("option[selected='selected']");
var machineValue = optionMachine.innerHTML;
var processValue = optionProcess.innerHTML;
var result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
if (machineValue != 'Product Machine' && processValue != 'Product Processing') {
result.innerHTML = machineValue + " " + processValue;
}
else if (machineValue != 'Product Machine') {
result.innerHTML = machineValue;
}
else if (processValue != 'Product Processing') {
result.innerHTML = processValue;
}
})()
So was able to get this to work by taking my JS and adding it in as a script within my functions.php. So essentially I was able to eliminate the custom_woocommerce_page_title filter.
Function.php
<?php
add_action('wp_footer', 'onLoadPageTitle');
function onLoadPageTitle() {
?>
<script>
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
</script>
<?php
}
?>
Then the woof woocommerce filter js that updates the title when a new select occurs after the AJAX.
(function() {
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
})()
will probably pare it down by just calling the script function from within the woof js after ajax.
Good afternoon. I am trying to pass the values associated with a list of checkboxes to a javascript function that then calculates the total for all values associated with selected checkboxes.
The HTML code is embedded within PHP. When I try to call the javascript function, I get a null result. Could anyone provide some pointers on where I am going wrong. Code below. All help is appreciated! Thank you.
The variables are pulled from the results of an SQL query executed just before the copied code below.
"<form action = 'book.php' method = 'POST'>
<tr><td>$seat</td>"
."<td>$zone</td>"
."<td>$price</td>"
."<td><input type = 'checkbox' id = 'seat['$seat']' value = '$price'></td></tr>"
//."<input type = 'hidden' id = '$seat' value = '$price' action = 'checkDetails()'>"
;
}
echo "</table>"
."Email address for booking ".
"<input type = 'text' name = 'email id'>"
." "
."<button type = 'submit' name = 'book' action = 'book.php'>Book</button></form>"
." "."<button name = 'check price' onclick = 'checkDetails()'>Check Prices</button>";
}
catch (PDOException $e) {
echo "PDOException: ".$e->getMessage();
}
echo "<script language = 'javascript'>
function checkDetails() {
var seat = document.forms[0];
var i;
for (i = 0; i < seat.length; i++) {
if (seat[i].checked) {
var total = document.getElementById('seat[i]');
alert('Your total is ' + total);
}
}
}
</script>";
You are looping through the forms length.
Since this is rendered in php why dont you set the length of of I programmatically
var i;
var length = <?= $seat?>;
for (i = 0; i < length; i++) {
if ( document.getElementById('seat[i]').checked) {
var total = document.getElementById('seat[i]');
alert('Your total is ' + total.value);
}
the following code is looping through the form and not the elements
var seat = document.forms[0];
var i;
for (i = 0; i < seat.length; i++) {
Hello I am new in PHP and JavaScript. I have a code of Dropdown Checkbox. I want to try get out values of checked options with comma separate like 1,2,3
My problem is that when i run my code my output have one extra comma at the end like 1,2,3, and my desired output is 1,2,3
Here is my code
HTML Part
<select id="agency" multiple="multiple">
<?php
if (is_array($rating_agencies) && !empty($rating_agencies)) {
foreach ($rating_agencies as $rating_agencie) {
echo '<option value="'.$rating_agencie->ID.'"';
echo '>';
echo $rating_agencie->name;
echo '</option>';
}
}
?>
</select>
<input type="button" id="btnSelected" value="Get Selected" />
Java Script
<script type="text/javascript">
$(function () {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
alert(message);
});
});
</script>
Use jQuery.map with Array#join
.get() will return basic-array instead of array-of-objects
$(function() {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function() {
var message = $("#agency option:selected").map(function() {
return this.value;
}).get();
alert(message.join(','));
});
});
Use slice to remove the last comma.
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
message = message.slice(0, -1);
alert(message);
});
This is your question solution, OR you can go with #Rayon.
Use slice function :
<script type="text/javascript">
$(function () {
$('#agency').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#agency option:selected");
var message = "";
selected.each(function () {
message += $(this).val() + ",";
});
message = message.slice(0, -1);
alert(message);
});
});
</script>
Try to get the value instead of option:selected, It may work for you
var selected = $("#agency").val();
use rtrim method in php
// $commaString = "1,2,3,";
$string = rtrim($commaString,",");
// output
// 1,2,3
in Javascript
var comma_string = "1,2,3,";
string = comma_string.replace(/,+$/,'');
You can use in either side as your logic.
Just use $rating_agencies = array_filter($rating_agencies) before your "if" statement.
I have two fields in my module called: rules_name_c which is a text field and rules_author_c which is a relate field.
These fields are not mandatory fields however when i enter data into the rules_name_c field I would like to make it so the rules_author_c must be filled in to complete the record.
I have tried the following:
<?php
$dependencies['conn_connection']['required_author'] = array(
'hooks' => array("edit"),
'trigger' => 'true', //Optional, the trigger for the dependency. Defaults to 'true'.
'triggerFields' => array('rules_name_c'),
'onload' => true,
//Actions is a list of actions to fire when the trigger is true
'actions' => array(
array(
'name' => 'SetRequired',
//The parameters passed in will depend on the action type set in 'name'
'params' => array(
'target' => 'rules_author_c',
'label' => 'rules_author_c_label',
'value' => 'not(equal($rules_name_c, ""))',
),
),
),
);
?>
I believe this solution will not work as this only functions when editing a record. Is that correct?
I have also tried using:
<?php
require_once('include/MVC/View/views/view.edit.php');
/*
* replace UT_Blogs with the module your are dealing with
*/
class conn_connectionViewEdit extends ViewEdit {
public function __construct() {
parent::ViewEdit();
$this->useForSubpanel = true; // this variable specifies that these changes should work for subpanel
$this->useModuleQuickCreateTemplate = true; // quick create template too
}
function display() {
global $mod_strings;
//JS to make field mendatory
$jsscript = <<<EOQ
<script>
// Change rules_author_c to the field of your module
$('#rules_name_c').change(function() {
makerequired(); // onchange call function to mark the field required
});
function makerequired()
{
var status = $('#rules_name_c').val(); // get current value of the field
if(status != ''){ // check if it matches the condition: if true,
addToValidate('EditView','rules_author_c','varchar',true,'{$mod_strings['LBL_RULES_AUTHOR']}'); // mark rules_author_c field required
$('#description_label').html('{$mod_strings['LBL_RULES_AUTHOR']}: <font color="red">*</font>'); // with red * sign next to label
}
else{
removeFromValidate('EditView','rules_author_c'); // else remove the validtion applied
$('#rules_author_c_label').html('{$mod_strings['LBL_RULES_AUTHOR']}: '); // and give the normal label back
}
}
makerequired(); //Call at onload while editing a Published blog record
</script>
EOQ;
parent::display();
echo $jsscript; //echo the script
}
}
I wrote this javascript function and later on I use it with jQuery:
function lxValidateCRMfield(form_name, field_name, label, validate, fnCallerName = "") {
fnCallerName = (fnCallerName != "") ? "(Function " + fnCallerName + ")" : "";
if (validate) {
console.log("lxValidateCRMfield adding validation on form " + form_name + " to field " + field_name, fnCallerName);
//addToValidate is defined somewhere on suitecrm
addToValidate(form_name, field_name, 'varchar', true, "Falta campo requerido: " + label);
$('#' + field_name + '_label').html(label + ': <font color="red">*</font>');
} else {
console.log("lxValidateCRMfield removing validation on form " + form_name + " to field " + field_name, fnCallerName);
//removeFromValidate is defined somewhere on suitecrm
removeFromValidate(form_name, field_name);
$('#' + field_name + '_label').html(label + ': ');
}
}
Then you call it on the form you need to (using your fields it could look like this):
// List all forms available
console.log(document.forms);
// select one you need
var form_name = 'EditView'; eg: EditView, DetailView, search_form
var module = 'YourModule'; // eg: Opportunities
var crmEditView = document.forms[form_name];
if (crmEditView.module.value == module) {
if ($('#rules_name_c').val() != '') {
lxValidateCRMfield(form_name, 'rules_author_c', 'Author', true, 'optionalNameOfFunctionYourCallingThis');
} else {
lxValidateCRMfield(form_name, 'rules_author_c', 'Author', false, 'optionalNameOfFunctionYourCallingThis');
}
}
I hope it helps
Regards
Here i am getting my Error Messages from a separate page and i am displaying it in a a div called #stage_error
$('#stage_error').html(error_string);
So, the errors will be displayed like this
The bus no field is required.
The comp id field is required.
The total seats field is required.
But what i want is to display the errors in its respective div's
i.e., the Bus no should be displayed near the div <div id='busno'> like this.
How can i do that ?
Json :
{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
Update :
Script for request and showing error :
<script>
$(document).ready(function() {
$("#driver").click(function(event) {
var BusNo = $("#BusNo").val();
var CompID = $("#CompID").val();
var TotalSeats = $("#TotalSeats").val();
var _token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
},
function(data) {
if (data != '') {
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
});
$('#stage_error').html(error_string);
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
</script>
Laravel Controller :
public function managebusregister()
{
$BusNo = Input::get('BusNo');
$CompID = Input::get('CompID');
$TotalSeats = Input::get('TotalSeats');
$data = Input::except(array('_token')) ;
$rule = array(
'BusNo' => 'required|unique:company_bus',
'CompID' => 'required',
'TotalSeats' => 'required|max:50'
) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return json_encode($validator->messages()); //php encoded value
}
else
{
DB::insert('insert into company_bus (BusNo, CompID, TotalSeats) values (?, ?, ?)',
array($BusNo, $CompID, $TotalSeats));
return '';
}
}
Html Code :
<div id="stage_error" style="color:red;font-size:15px"></div>
<div id="stage_success" style="color:green;font-size:20px"></div>
and beyond that i have each field input boxes,
<input type="text" id="BusNo" name="BusNo"/>
<input type="text" id="CompID" name="CompID"/>
How can i throw error messages near the respective fields
Below is the approach: Observe I've added spans with error after text boxes.
CSS
<style>
.error { color:red; font-size:15px; }
</style>
Html
<input type="text" id="BusNo" name="BusNo" /><span class="error"></span>
<input type="text" id="CompID" name="CompID" /><span class="error"></span>
JavaScript I did some changes as per the jQuery standard, it should work well, if you're not interested then you can ignore all the changes but can take only below mentioned if logic block.
The error display added in if (!data) {...}
$(function () {
$(document).on("click", "#driver", function (event) {
var BusNo = $("#BusNo").val(),
CompID = $("#CompID").val(),
TotalSeats = $("#TotalSeats").val(),
_token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
}).done(function (data) {
$("span.error").empty();//All previous error messages cleared here.
if (!data) {
var obj = JSON.parse(data);
//obj = {"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
$.each(obj, function (entry) {
var targetSelector='';
if (entry == "busno") {
targetSelector = "#BusNo";
}
if (entry == "Comp Id") {
targetSelector = "#CompID";
}
if(targetSelector) //Here we're setting error message for respective field
$(targetSelector).next("span.error").html(obj[entry]);
});
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
you can try like this:
var json = JSON.parse('{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}');
// alert(json['busno']);
$("#busno").html(json.busno);// like this for others also.
change here:
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
if(entry == 'busno'){
$("#busno").html(obj[entry]);// like this for others also.
}
if(entry == 'Comp Id'){
$("#compid").html(obj[entry]);// like this for others also.
}
});
$('#stage_error').html(error_string);