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.
Related
I have WebGrid on MVC project with two WebGrid column. The first column collapses the sub-data and the other column is for checkbox.
This checkbox will check all checkbox on its subdata. The problem is I cannot select all the data on its sub-checkbox. This is my sample code:
//This colum will generate checkbox for the main data
wbclCol.Add(new WebGridColumn
{
ColumnName = "",
Header = "",
CanSort = false,
Format = (objChildItem) =>
{
StringBuilder strbHtml = new StringBuilder();
strbHtml.Append("<input class='obj-parmain' name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
return new MvcHtmlString(strbHtml.ToString());
}
});
//This column will generate another column for the sub-data:
wbclCol.Add(new WebGridColumn
{
ColumnName = "",
Header = "",
CanSort = false,
Format = (objChildItem) =>
{
StringBuilder strbHtml = new StringBuilder();
strbHtml.Append("<input class='obj-parsub' name='lngID' value='" + objChildItem.lngPARID + "' data-pardata='" + objChildItem.lngID+ "' data-show='True' type='checkbox' ></input>");
return new MvcHtmlString(strbHtml.ToString());
}
});
This is my javascript to select all checkbox on class: obj-parsub when my checkbox with class: obj-parmain is check
function fncParMainCheck() {
$(document).off('click', '.obj-parmain');
$(document).on('click', '.obj-parmain', function (e) {
var blIsCheck = $(this).is(':checked');
if (blIsCheck) {
//var objNext = $('.obj-parsub').nextAll();
//var objNextMain = $(this).siblings().nextAll().find('.obj-parsub');
//var objNextMain = $(this).closest('.obj-parmain').find('.obj-parsub').prop('checked', this.checked);
$(this).closest('.obj-parmain').find('.obj-parsub').parent().parent().nextAll().prop('checked', this.checked);
//$(objNextMain).prop('checked', blIsCheck);
}
});
}
try with this code. first you check your checkbox is checked or not.
$(document).on('change', '.obj-parmain', function (e) {
if ($(this).is(':checked')){
$('input:checkbox.obj-parsub').prop('checked', $(this).prop('checked'));
}
else{
// uncheck logic
}
});
Try like this
$(document).on('change', '.obj-parmain', function (e) {
$('.obj-parsub input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
If you encounter the same problem, this works pretty well:
function fncParMainCheck() {
$(document).off('click', '.obj-parmain');
$(document).on('click', '.obj-parmain', function () {
var blIsCheck = $(this).is(':checked');
if (blIsCheck) {
//This will look for the sublist of checkbox that is under class name obj-parsub and checks everything
var objNext = $(this).parent().parent().find('.obj-parsub');
$(objNext).prop('checked', blIsCheck);
}
});
}
There is 2 input type="text". First, user input 1st input text area with id="ncr_no". Then, cursor is in 2nd input type "text" with id="itm_cd". Now, I want to make, how the two input by user, when cursor is in 2nd input type, posted to other php (get_ncrnoitmcd.php) by javascript? That's the code.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){$("#user-result3").html('');return;}
if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post('get_ncrnoitmcd.php', {'itm_cd':itm_cd}, function(data) {
$("#user-result3").html(data);
});
}
});
});
</script>
Thank a lot.
This is the way you can send the 2 values to server on 2nd element keyup after validation. Whats the problem that you are facing? I also added ncr_no in the post request.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){
$("#user-result3").html('');
return;
}else if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post(
'get_ncrnoitmcd.php'
,{'itm_cd':itm_cd,'ncr_no':$('#ncr_no').val()}
,function(data) {
$("#user-result3").html(data);
}
);
}
});
});
</script>
I want to get available or not available, Mr. #joyBlanks
<?php
//connection.php
if(isset($_POST["itm_cd"],$_POST["ncr_no"]))
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
$itm_cd = strtolower(trim($_POST["itm_cd"]));
$itm_cd = filter_var($itm_cd, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$results = mysqli_query($connecDB,"SELECT itm_cd,ncr_no FROM sqc_ncr WHERE itm_cd ='$itm_cd' AND ncr_no ='$ncr_no'");
$itm_cd_exist = mysqli_num_rows($results);
if($itm_cd_exist) {
die('<!--img src="image/available.png" /--> <i>Available in database</i>');
}else{
die('<!--img src="image/not-available.png" /--> <i>Not Available in database</i>');
}
mysqli_close($connecDB);
}
?>
I've not used , and used && and not used http_x_requested, but available or not available in html not shown.
<td><input type="text" class="input" name="itm_cd" id="itm_cd" onBlur="updateItemName()" required /> <span id="user-result3"></span></td>
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);
I have a code that counts down and when the countdown reaches 0 I want it to grab data from a MySql table and present it on the page without reloading.
I know my countdown works, but it is when I add the code to get the data from the PHP page it stops working. I know my PHP page works and grabs the correct data and presents it.
Here is the code I am currently using.
Any ideas?
<div id="countmesg"></div>
<div id="checking"></div>
<div id="name-data"></div>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var delay = 10;
function countdown() {
setTimeout(countdown, 1000);
$('#countmesg').html("Auction ends in " + delay + " seconds.");
delay--;
if (delay < 0) {
$('#countmesg').html("Auction ended.");
delay = 0;
}
}
countdown();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var delay = 2;
function countdown() {
setTimeout(countdown, 100);
$('#checking').html("Checking in " + delay + " seconds.");
delay--;
if (delay < 0) {
$('#checking').html("Checking again....");
var name = 'tom';
$.post('cdown.php', {
name: name
}, function (data) {
$('div#name-data').text(data);
};
delay = 2;
}
}
countdown();
});
</script>
The 3 lines that are supposed to be grabbing the PHP file are:
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').text(data);
PHP Code:
<?php
require 'connect.php';
$name = 'tom';
$query = mysql_query("
SELECT `users`.`age`
FROM `users`
WHERE `users`.`name` = '" . mysql_real_escape_string(trim($name)) . "'"
);
echo (mysql_num_rows($query) !== 0) ? mysql_result($query, 0, 'age') : 'Name not found';
?>
use $.ajax instead of $.post
$.ajax(//url to php//).done(
function (data) { //data is from the php
//do stuff
}
)
Code you provided (3 lines):
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').text(data);
It seems like you have an incomplete $.post(...) statement. If you check your Console you should see some Exceptions. What are they?
Update your 3 lines to this:
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').html(data);
});
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() {