This question already has answers here:
Fastest way of deleting a value in a comma separated list
(4 answers)
Closed 6 months ago.
I want to remove one value from comma separated string variable
Eg hdnListCL ="'ABC','PQR','XYZ'"
i want to remove any one of them, how i can do this without converting this into array?
html code
<input type="hidden" name="hdnlistCL" id="hdnlistCL"/>
<table>
<tr>
<td>
<div id="ProjList"><?php print $strLocName; ?></div><br/>
<input type="text" name="txtCommonLocation" id="txtCommonLocation" size="40" value=""/>
<img src="images/plus.gif" title="Click Here" onclick="AddNewLocation()" style='cursor:pointer;' align="right"/> </td>
</tr>
</table>
javascript
<script type="text/javascript" src="../scripts/jquery.min.js"></script>
<script type="text/javascript">
function AddNewLocation()
{
var listCL = "";
this.strProjName;
if ( typeof strProjName == 'undefined' ) {
strProjName = '';
}
var newLoc = document.getElementById('txtCommonLocation').value;
document.getElementById('txtCommonLocation').value = "";
if(document.getElementById('hdnlistCL').value == '')
{
document.getElementById('hdnlistCL').value =newLoc;
}
else
{
document.getElementById('hdnlistCL').value += ","+newLoc;
}
listCL = newLoc;
if(listCL != '')
{
strProjName = strProjName + '<div id="'+listCL+'">'+listCL+'<div class="close" onclick="removeLocation(\''+listCL+'\')"></div></div>';
}
// alert(strProjName);
$('#ProjList').html(strProjName);
}
function removeLocation(pLocation)
{
var hdnListLocation = document.getElementById('hdnlistCL').value;
if(window.confirm("Are you sure you want to delete this?"))
{
url = 'test_st.php';
$.post(
url,
{"act":"Delete","DelLocation":pLocation,"hdnListLocation": hdnListLocation},
function(responseText){
alert(responseText);
return false;
window.location="test_st.php";
},
"html"
);
return false;
}
}
</script>
php code
<?php
if(isset($_POST['act']))
$act = $_POST['act'];
if($act == "Delete")
{
$arrhdnListLocation = explode(",", $_POST['hdnListLocation']);
if(in_array($_POST['DelLocation'],$arrhdnListLocation))
{
print("I want to remove'".$_POST['DelLocation']."' from hdnlistCL");
exit();
}
else
{
print("No");
exit();
}
}
?>
when i click close button i want to remove that location from hdnlistCL. how i can do this?
value of hdnListCL is ABC,PQR,XYZ i want to remove PQR from this
$string = "'ABC','PQR','XYZ'";
$remove = "'PQR'";
// you can use array_diff method to remove specific array item
$result = array_diff(str_getcsv($string), array($remove))
echo implode(',', $result); // output is "'ABC','XYZ'"
php fiddle example: http://phpfiddle.org/main/code/v260-p3cf
Please Try this
$hdnListCL ="'ABC','PQR','XYZ'";
$hdnListCL=explode(',',$hdnListCL);
$index = array_search('PQR',$hdnListCL);
if($index !== false){
unset($hdnListCL[$index]);
}
$hdnListCL=implode(',',$hdnListCL);
print_r($hdnListCL);
Related
I am looking for some initial direction on this one because I cannot seem to find my way with it. Let me explain... I'm creating a music website and having a search bar. It filters information as the user types. I don't want to make a separate .php file for each song on the website. (Eg: song1.php, song2.php, etc...). There should be one PHP template file, that outputs the webpage for ALL songs. With my code, when I try searching with the search bar, it opens the template file as expected but it fills the file with information of only the first row from the mysql table. This is the form, its in the index page:
<script type = "text/javascript "src = "jquery.js">
<form class="navbar-form navbar-left" >
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search for songs, artists" autocomplete="off">
<div id = "searchresults"> </div>
Then there's the search.js file having two tasks, that is to check if a result has been clicked and also if the user has pressed a key. Its like this:
$('#search').keyup(function()
{
var searchterm = $ ('#search').val();
if (searchterm != '')
{
$.post('search.php', {searchterm:searchterm},
function(data)
{
$('#searchresults').html(data);
});
}
else{
$('#searchresults').html('');
}
});
$('#mylink').click(function(){
var wanted = $('#mylink').val();
$.post('/web/ztemplate.php', {wanted:wanted});
});
I think it's the one having an error but I can't figure out where it is. The template file has this php code :
$search = $_POST['wanted'];
$find = mysql_query("SELECT * FROM search WHERE title LIKE '%$search%'");
$row = mysql_fetch_assoc($find); $title = $row["title"];
There's a search.php file which queries the database to provide information for the instant search. It looks like this :
$search = mysql_real_escape_string(trim($_POST['searchterm']));
if ($search == '' && ' '){
echo 'No results found';
}
else {
$find_videos = mysql_query("SELECT * FROM search WHERE keywords LIKE '%$search%'");
$count = mysql_num_rows($find_videos);
if ($count ==0){
echo 'No Results found for '.$search;
}
else {
while($row = mysql_fetch_assoc($find_videos)){
$title = $row["title"];
$link = $row["link"];
echo "<a href = '$link'><h5 id = 'mylink'> $title <h5> </a> <hr /> ";
}
}
}
Any help is much appreciated.
why you not send an AJAX??
$('#search').keyup(function(){
var searchterm = $ ('#search').val();
if (searchterm != ''){
$.ajax({
type: 'POST',
data: {
"searchterm": searchterm,
"_token":"{{ csrf_token() }}"
},
url: "{{URL::asset('yourPHP')}}",
success: function(response){
$('#searchresults').html(response);
}
});
}else{
$('#searchresults').html('');
}
});
PHP
function searchSong($search =''){
$search = (trim($_POST['searchterm']));
$out='';
if ($search == '' && ' '){
echo 'No results found';
}else {
$sql = "SELECT * FROM search WHERE title LIKE '%$search%'";
$data= DB::select($sql);
$count = count($data);
if ($count ==0){
echo 'No Results found for '.$search;
}else {
foreach ($data as $key => $row) {
$title = $row["title"];
$link = $row["link"];
$out .= "<a href = '$link'><h5 id = 'mylink'> $title </h5> </a> <hr /> ";
}
}
}
return $out;
}
I have a search filter based on flags of different colors.
If I will search based on color it is showing result but when I will select white color flag it is showing entire data in my database table. But If I choose any other color apart from white color for the first time it will show result. And if I choose white color flag second time,then it gives the correct result. What might be the reason. I need help
//filter on flag_color
if($this->input->get('flg')){
$arr_flag = explode('-', $this->input->get('flg'));
$str_flag = implode(',',$arr_flag);
if(6 == $str_flag){
$str_flag = 0;
}
$str_condition .= 'AND t.sender_flag_color_id IN('.$str_flag.')';
}
array(
'0'=>array(
'color'=>'White',
'path'=>'whiteflag.png'),
'1'=> array(
'color'=>'Blue',
'path'=>'blueflag.png'),
'2'=>array(
'color'=>'Green',
'path'=>'greenflag.png'),
'3'=>array(
'color'=>'Yellow',
'path'=>'yellowflag.png'),
'4'=>array(
'color'=>'Red',
'path'=>'redflag.png') ,
'5'=>array(
'color'=>'Orange',
'path'=>'orangeflag.png')
);
view
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
if(isset($arr_params['flg']))
{ ?>
<input type="hidden" id="flag_in_url" name="flag_in_url" value="yes" />
<?php
}
?>
<!-- id="webmenu1" -->
<select class="flag_color" onchange="urgency_select('flag_color')" name="header_flag" id="webmenuflag1">
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
$int_flag_url = '';
if(isset($arr_params['flg']))
{
$int_flag_url = $arr_params['flg'];
}
if(isset($arr_flag_color))
{
foreach($arr_flag_color as $key=>$flag_color)
{
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
else
{
$flag_selected = '';
}
?>
<option <?php echo $flag_selected;?> value="<?php echo $key;?>" data-image="<?php echo base_url();?>images/<?php echo $flag_color['path'];?>"></option>
<?php
}
}
?>
js: urgency_select
var flag_color_id = '';
if(select_option == 'flag_color' || $( "#flag_in_url" ).val() == 'yes')
{
if($( ".flag_color" ).val() != undefined)
{
var flag_color_id = $( ".flag_color" ).val();
if(flag_color_id == 0)
flag_color_id = 6;
search_url += 'flg/'+flag_color_id+'/';
}
}
Its because conflict with the value of white color flag...
In the view I changed the code
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
to
if($int_flag_url == 0 || $int_flag_url == $key)
{
$flag_selected = 'selected';
}
a user checks the type of zones and choose the type of change; this script will load the change description details from a database into a textarea field in html.
Then what I want to happend next is:
the descriptions text gets appended with the different zones the changes will take place within the html description textarea. I do not want the zones to be appended to my description data in my database. The issue is the appending of the different zones to the description field is not working..
I am using javascript to append the text. Can someone advice me why I need to correct my code?
<html>
<head>
<script language="JavaScript" type="text/javascript">
// who says we found anything? Maybe this id does not even exist.
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?change_type='+value;
data_center = [],
data_centers = "";
inputs = document.getElementsByTagName('input');
for (var x = 0, len = inputs.length; x < len; x++) {
{
if (inputs[x].type == "checkbox" && inputs[x].name == 'data_center[]') {
if (inputs[x].checked === true) {
data_center.push(inputs[x].value);
}
}
}
data_centers = (data_center.length > 0 ? ': ' + data_center.join(', ') : '') + '.';
document.getElementById('description').value += data_centers;
document.getElementById('impact').value += data_centers;
}
}
</script>
</head>
<?php
require_once("db_handler.php");
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['change_type'])) {
$change_type = mysql_real_escape_string($_REQUEST['change_type']);
} else {
$change_type = False;
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec) {
trigger_error("Cannot fetch data from change table: " . mysql_error(), E_USER_ERROR);
}
if (0 == mysql_num_rows($exec)) {
trigger_error("There are no changes in the 'change' table. Cannot continue: it would not work. Insert some changeids and retry.", E_USER_ERROR);
}
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['changeID'] === $change_type)
// who says we found anything? Maybe this id does not even exist.
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $change_type)
$change_type = $row['changeID'];
$sel = '';
}
$options .= "<option value=\"{$row['changeID']}\" $sel>{$row['changeName']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['description']))
{
$change_data = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO change ( changeID, description ) VALUE '{$change_type}', '{$change_data}' ) ON DUPLICATE KEY UPDATE description=VALUES(description);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
// abbreviated unchanged code.
$query = "SELECT `description`, `impact` FROM `change` WHERE `changeID`='{$change_type}';";
$exec = mysql_query($query);
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textareaDescription = $row['description'];
$textareaImpact = $row['impact'];
} else {
$textareaDescription = '';
$textareaImpact = '';
}
mysql_free_result($exec);
?>
<body bgcolor="white">
<form name="changeform" method="post" action="email_form.php">
<table>
<tr valign="top">
<td><b>Data Center</b></td>
<td><input name="data_center[]" type="checkbox" value="[Zone10]"/>[Zone10]
<input name="data_center[]" type="checkbox" value="[Zone11]"/>[Zone11]
</td>
</tr>
<tr valign="top">
<td><b>Change Type</b></td>
<td><select id="change_type" name="change_type" onChange="getData(this)""><?php print $options; ?></select></td>
</tr>
<tr valign="top">
<td><b>Description</b></td>
<td><textarea name="description" id="description" cols="50" rows="10"><?php print $textareaDescription; ?></textarea></td>
</tr>
<tr valign="top">
<td><b>Service Impact</b></td>
<td><textarea name="impact" id="impact" cols="50" rows="10"><?php print $textareaImpact; ?></textarea></td>
</tr>
<tr valign="top">
<td align="center" colspan="2"><input type="submit" value="submit change" /></td>
</tr>
</table>
</form>
</body>
</html>
The following lines look like there might be something wrong:
for (var x = 0, len = inputs.length; x < len; x++)
{
{
Unless that is syntax that I'm just not familiar with.
Is there any way you could show us the actual code, running? Looking at something like this is a bit hard to digest without being able to see it in action.
First time posting, hope all goes well :)
Been working on this for a while but basically I'm doing something like this: http://drupal.org/project/fancycheckboxes
I need to set a value of yes/no for each checkbox that I'm looping through and right now it works but is changing the value of all when I change one.
My foreach loop:
<?php $object = new stdClass(); $i = 0; ?>
<?php foreach( $filters as $key => $value ) {
?>
<tr>
<td><label for="show_filter">Show <?php echo $object->$key = $value['filter']; ?> Filter</label></td>
<td><input type="checkbox" class="show_filter" <?php //if ( $row['active_filter'] === 'yes' ) { ?>checked="checked"<?php //} ?> name="dp_show_filter" value="<?php echo $object->$key = $value['active_filter']; ?>"/><?php echo $object->$key = $value['active_filter']; ?></td>
<td><a class="button-primary" href="?page=profolio_theme&del=<?php echo $row['id'];?>">Delete</a></td>
</tr>
<?php
$i++;
}
and my jQuery:
jQuery(document).ready(function(e) {
var $ = jQuery.noConflict();
$i = 0;
customCheckbox = $('.dp_wrap input[type="checkbox"]');
showFilter = $('.dp_wrap input[name="dp_show_filter"]');
values = [];
return customCheckbox.each(function() {
// the element
var el = this;
// Hide checkbox
$(this).hide();
// Replace element
var rep = $('<span></span>').addClass('dp-checkbox').insertAfter(this);
// default state
if( $(showFilter).val() === 'yes'){
$(showFilter).prop('checked', true);
$(rep).removeClass('off').addClass('on');
} else {
$(showFilter).prop('checked', false);
$(rep).removeClass('on').addClass('off');
}
if($(this).is(':checked') ) {
$(rep).addClass('on');
} else {
$(rep).addClass('off');
}
// Click event
$(rep).click(function(e) {
e.preventDefault();
if( $(el).is(':checked') ) {
values.push($(showFilter).val('no'), ++$i);
$(el).prop('checked', false);
$(rep).removeClass('on').addClass('off');
} else {
values.push($(showFilter).val('yes'), ++$i);
$(el).prop('checked', true);
$(rep).removeClass('off').addClass('on');
}
});
});
});
Currenty my values are posting to a database as yes/no.
Any help is greatly appreciated and I hope my first post is an acceptable one.
It is changing all of the values as it looks as though you are giving the same name to every checkbox created on your page.
You can change your PHP code to something more like this:
<?php $object = new stdClass(); $i = 0; ?>
<?php foreach( $filters as $key => $value ) {
?>
<tr>
<td><label for="show_filter">Show <?php echo $object->$key = $value['filter']; ?> Filter</label></td>
<td><input type="checkbox" class="show_filter" <?php //if ( $row['active_filter'] === 'yes' ) { ?>checked="checked"<?php //} ?> name="dp_show_filter_<?php echo $row['id'] ?>" value="<?php echo $object->$key = $value['active_filter']; ?>"/><?php echo $object->$key = $value['active_filter']; ?></td>
<td><a class="button-primary" href="?page=profolio_theme&del=<?php echo $row['id'];?>">Delete</a></td>
</tr>
<?php
$i++;
}
Then change your default state to this and remove the if statement from underneath it:
// default state
if( $(this).val() === 'yes'){
$(this).prop('checked', true);
$(rep).removeClass('off').addClass('on');
} else {
$(this).prop('checked', false);
$(rep).removeClass('on').addClass('off');
}
I am pretty sure that will fix your problem as you described it. It is hard to tell without a more complete example of your code.
You iterate through your customCheckbox array with an each, but inside your loop, you access $(showFilter), which is a global array.
Did you mean $(showFilter[i]) ?
The each callback receives i (the index in the loop) as a parameter :
return customCheckbox.each(function(i) {
...
if( $(showFilter[i]).val() === 'yes'){ ...
This is the content on my view page and i want to replace the value from "0" when the monthfunc() is called...the monthfunc() is given below the view content
<tr>
<td>
<input type="submit" name="monthplus" id="monthplus" onClick="return monthfunc('monthplus');" value=">>>>>>">
<input type="hidden" name="monthnum" id="monthnum" value="1">
<input type="text" name="monthname" id="monthname" value="0" value="<? echo $month;?>" >
<input type="submit" name="monthminus" id="monthminus" onClick="return monthfunc('monthminus');" value="<<<<<<">
</td>
</tr>
My script is
function monthfunc(mnth)
{
if(mnth == 'monthplus')
{
var yn = document.getElementById('monthnum').value;
ynpo = parseInt(yn)+1;
if(ynpo==13)
{
ynpo=1;
}
}
else if(mnth == 'monthminus')
{
var yn = document.getElementById('monthnum').value;
ynpo = parseInt(yn)-1;
if(ynpo==0)
{
ynpo=12;
}
}
if(ynpo ==1)
{
document.getElementById('monthname').value = 'january';
document.getElementById('monthnum').value = ynpo;
return true;
}
else if(ynpo ==2)
{
document.getElementById('monthname').value = 'february';
document.getElementById('monthnum').value = ynpo;
return true;
}
else if(ynpo ==3)
{
document.getElementById('monthname').value = 'March';
document.getElementById('monthnum').value = ynpo;
return true;
}
return false;
}
How can i replace The value with the value like january february etc..
Actually i can change the values but cannot retain the values...
i want to retain the values ,,,How to do that
For the monthname input you have two 'values'. What happens when you remove the first one?
Also, you really need to improve the structure of your function. For example, using the following array would reduce your code significantly:
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
I'm not sure I exactly understand your question, but by way of an answer:
One of the input elements in your HTML snippet has two value attributes:
value="0"
and
value="<? echo $month;?>"
I would start by removing one of them.