deduplicates values in array with javascript before GET query - javascript

I have the following loop that list domains. Each line contains a checkbox with domain as value stored in array urls[] :
<form action="/profiles-routing/add/63" method="get">
...
<?php foreach ($accesslogs as $accesslog): ?>
<tr>
<td>
<input class="checkbox" type="checkbox" name="urls[]" value="<?= $accesslog->DOMAIN ?>">
</td>
<td><?= $accesslog->DOMAIN ?></td>
</tr>
<?php endforeach; ?>
...
</form>
I could have many same domains in the query, I looking how to deduplicate urls values with a javascript before doing the GET query.
For example, javascript should modify this :
http://127.0.0.1:8001/profiles-routing/add/63?urls[0]=www.domaine1.com&urls[1]=www.domaine1.com&urls[2]=www.domaine1.com&urls[3]=www.domaine2.com&urls[4]=www.domaine2.com
To this :
http://127.0.0.1:8001/profiles-routing/add/63?urls[0]=www.domaine1.com&urls[3]=www.domaine2.com
How can I do it ?
Thank you,

I came up with this code to help you out:
<?php
function arr_clearduplicates($arr) {
$newArray = array();
foreach($arr as $val) {
//If the value isn't in the array, push it in.
// This will make sure no existing data is added again.
if(!in_array($val, $newArray)) {
$newArray[] = $val;
}
}
return $newArray;
}
?>
This will basically register a function doing this:
Take whatever array you give it
Make a new empty array.
Take all values in your first array, if they are already in the new array, they will not be added, otherwise, they will.
Return the empty array.
Which means: array will have no values equal to each other.

Related

The first table row (dynamically generated) always shows, no matter the input value for Javascript

Sorry for asking, I am probably missing something small here but have no clue. I dynamically generated a long list of radio buttons using PHP. On top of the list is an HTML input to search through the list using jQuery. This works, except for one tiny detail. The first radio button in the list always shows, no matter what the search result is. Even if I type something completely different, I will always see the first radio button in the list together with the matching results.
What is going wrong here?
This is my dynamically generated list of radio buttons, using HTML and PHP:
<input id="addplantSearch" class="form-control" type="text" name="addplantsearch" placeholder="Zoek op (Latijnse) naam..." style="margin:0; height:48px;"> <!-- Search input -->
<?php
$query = "SELECT * FROM plants ORDER BY plants.name ASC;";
$post_data = $data->execute($query);
// Prepared statement in 'execute' method (Database class)
?>
<div class="addplant-list">
<?php
foreach ($post_data as $post) {
# Loop start
?>
<div class="searchable">
<label class="pselect-container"> <?php echo $post['name']; ?>
<input type="radio" name="selectPlant" value="<?php echo $post['plant_id']; ?>">
<span class="pselect-checkmark" style="width:100%;">
<img src="../system/src/img/plants/<?php echo $post['directory']; ?>/icon.png" />
<?php echo $post['name'] . " - (" . $post['name_latin'] . ")"; ?>
</span>
</label>
</div>
<?php
# Loop end
}
?>
</div>
And this is my jQuery, responsible for searching through the list:
$("#addplantSearch").keyup(function() {
var value = this.value;
$(".addplant-list").find(".searchable").each(function(index) {
if (!index) return;
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
});
EDIT: The first item in the list is determined by the alphabetical order (ASC) of my database results (see $query variable). So this is always the same item in alphabetical order.
It looks like your issue is with your if statement.
if (!index) return;
This problem occurs because JavaScript uses 0 based arrays, and 0 is also a falsy value. Meaning:
!0 === true
and the first item in the array will always return out of the function and won't be applicable to the toggle logic.
So probably a lot of ways to work around this, one would be to check the length of the array before the each function. Ex:
$("#addplantSearch").keyup(function() {
var value = this.value;
var searchableItems = $(".addplant-list").find(".searchable");
if (searchableItems.length) {
searchableItems.each(function(index) {
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
}
});

How to get class array index for getElemetByClass name in JavaScript

everyone. I'm still new using JavaScript, I need your help to fix my problem, I try to disable checkbox after submitted. Because my checkbox value is from DB and the data will show as long as the DB have it so I'm using class="select_DB[]" in my input tag. From my knowledge class is using array index so I want to disable the checkbox that I choose I have to get the array index of the class. So how I can get the array index of the checkbox ? Need you help
//this code for disable checkbox after submit need improve I don't know how to get array index of the class
function closeCB() {
document.getElementByClassName("select_DB").disabled = true;
}
<tbody>
<?php
include "db_connect.php";
$sql_select = $dt_bas->prepare("SELECT id_pegawai, nm_pegawai, tmp_lahir FROM pegawai");
$sql_select->execute();
while($row = $sql_select->fetch(PDO::FETCH_ASSOC)){
$id = $row["id_pegawai"]; // id
$nm = $row["nm_pegawai"]; // employe name
$tmp = $row["tmp_lahir"]; // birthday
?>
<tr>
<td><input type="checkbox" class="select_DB[]" class="select_DB[]" value=<?php echo"$id";?> <?=was_checked($id)?>/></td> <!-- This is the checkbox-->
<td><?php echo "$id";?></td>
<td><?php echo "$nm";?></td>
<td><?php echo "$tmp";?></td>
<td>
Ubah
Detail
</td>
</tr>
<?php } ?>

selecting html checkbox based on json array values

I have form where i am sending multiple checkbox items as array to controller,
<?php
foreach($groupsArray as $group)
{
?>
<label>
<input type="checkbox" class="icheck" name="groups[]" id="groups" value="<?php echo $group["id"];?>"> <?php echo $group['name']?> </label>
<?php
}
?>
Everything works fine for checkbox values update in database,
Now, what i am doing is, getting values from database and i need to check values which are stored in database,
I am getting below json response from PHP<
groups: [{user_id: "2", group_id: "4", id: "4", name: "system Creators",…}]
Below i used as AJAX
if(objData.groups[0].group_id == $("#groups").val())
{
$("#groups").iCheck('check');
}
With this $("#groups").val(), it always takes values of first checkbox, so there is problem,
How can i compare values for all checkboxes with Json?
Also if groups array will have multiple values, means multidimensional array, more groups then?
Thanks in advance!
You need to be able to know which checkbox is related to which database value.
That is what the ID is used for on the checkbox. You have them all the same being "groups" - which is bad practice.
Use: (note the dynamic id attribute)
<?php
foreach($groupsArray as $group)
{
?>
<label>
<input type="checkbox" class="icheck" name="groups[]" id="chk<?php echo $group["id"];?>" value="<?php echo $group["id"];?>"> <?php echo $group['name']?> </label>
<?php
}
?>
Then loop around your group object from the database:
for(var i = 0; i < groups.length; i++) {
var chk = document.getElementById("chk" + groups[i].id);
chk.checked = true;
}
Try this:
PHP:
<?php
$count=0;
foreach($groupsArray as $group)
{
?>
<label>
<input type="checkbox" class="icheck" name="groups[]" id="groups<?php echo $count;?>" value="<?php echo $group["id"];?>"> <?php echo $group['name']; ?> </label>
<?php
$count++;
}
?>
Jquery:
for(var i=0;i<objData.gourps.length;i++){
if(objData.groups[i].group_id == $("#groups"+i).val())
{
$("#groups"+i).iCheck('check');
}
}
First, change the groups checkbox's id to it's class, so use class="groups" instead of id="groups", like this:
<label><input type="checkbox" class="icheck" name="groups[]" class="groups" value="<?php echo $group["id"];?>"> <?php echo $group['name']?> </label>
Next, use the jQuery .each method to check all the checkboxes that is found in the JSON object like this:
$.each(objData, function(n, i){
if(i.group_id == $(".groups[name="+n+"]").val()){
$(".groups[name="+n+"]").iCheck('check');
}
});
Finally, this worked!
Find only those checkboxes which are coming from DB and check those.
for(var i = 0; i < objData.groups.length; i++)
{
$("#groups" + objData.groups[i].group_id).iCheck('check');
}
Thanks all for support!

How do I attach checkboxes to a submit

I have unknown amount of checkbox inputs on a page created based on rows in an sql database.
The checkboxes look like:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
The checkboxes are intended, when checked and submitted, to delete a row from the database based on the value of $mid
The checkboxes could be either loose (not contained in any forms), or each could be contained in its own form (without a submit button). There is no way however to contain all the checkboxes in one form.
The reason is it's displayed in a loop with output like this:
<tr>
<td><input type="checkbox" class="deletefunc" value="<? echo $mid; ?>"></td>
<td><input type="checkbox" class="star" value="1"> <!-- jquery/ajax onclick function --></td>
<td><a href></td>
<td><form name....><input type="submit" value="something"></form></td>
<tr>
So what I need help understanding is, how to gather all the checkboxes based on classname, and attach them to a submit button....
And further, how would I write the loop function so it knows how many deletes to perform? What I mean is, how would I write a loop that would get the values from an unknown amount of inputs. Normally I know how many inputs there are and what the names are so its a matter of assigning a variable for each input.... I've never done this with an unknown amount of inputs.
I would do it like this:
HTML:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<button id="delete-them">Delete Them</button>
JS:
$(function() {
$('#delete-them').on('click', function() {
var data = $('.deletefunc').attr('name', 'delete[]').serialize();
$.ajax('delete-them.php', {
method: 'POST',
data: data,
success: function() {
alert('deleted!');
}
});
});
});
PHP:
<?php
$ids = $_POST['delete'];
$params = array_fill(0, count($ids), "?");
$sql = "DELETE FROM some_table WHERE id IN (" . implode(",", $params) . ")";
//DELETE FROM some_table WHERE id IN(?,?,?,?);
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
?>
So we basically listen for a click on our button, when it happens, we set the name (with [] at the end so it becomes an array) for all of the items with the class we care about, so that when we serialize those items we know how to reference it in our PHP.
We then POST that data over to the server, where we read the array we just sent, see how many there are, and then create a query to delete those items.

Clear input field value after javascript alert

I have a dynamic field that get value from database, and I want to check one of the field value if it was greater from the old value or not. If it does greater, i have to give an alert and reset field value back to ''
i want to do it without using document.GetElementById because the field was looped by foreach, I'm tryin to work with document.GetElementByName but got no where. here's my code
<?php foreach ($items->result_array() as $row){ ?>
<tr>
<td><p><?php echo $row['nmbr']; ?> </p>
<p><?php echo $row['urai']; ?><p> </td>
<td><?php echo $row['jml']?> </td>
<td><div class="oldprice"><?php echo $row['oldprice']?></div></td>
<td><input id="pnwrn" class="pnwrn" type="text" name="pnwrn[]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
<td><div class="output"></div></td>
</tr>
<?php } ?>
and this is my javascript :
<script type="text/javascript">
$('.pnwrn').on('change', function () {
var twrn = $(this).val();
var price = parseInt($(this).data('harga'));
var jmlh = parseInt($(this).data('jumlah'));
if (twrn <= jmlh){
$(this).parents('tr').find('.output').html(twrn*price);
}
else {
alert("Price can not be greater from old price");
cleartext();
}
});
function clearInputs() {
document.getElementByName("pnwrn").value = "";
}
</script>
can someone help me?
You are not supposed to have multiple elements with the same id. Instead, try this:
<td><input id="pnwrn<?php echo $row['some_id_field_that_you_have']; ?>" class="pnwrn" type="text" name="pnwrn[<?php echo $row['some_id_field_that_you_have']; ?>]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
You can also attach the matching ID on the <tr>, or to other elements, which makes it trivial to find the appropriate elements.
Unfortunately, with names like urai, harga, jumlah and pnwrn, it is extremely hard to pinpoint what exactly you're trying to do, thus just vague hints.
But - if you're trying to clear the very field you're checking, you already have it, so no lookup needs to be done. Just do clearInput(this).
Try this to loop through all the inputs and match on the class you want:
$("input").each(function (i) {
if ($(this).prop("class") === "pnwrn") {
$(this).val('');
}
});

Categories

Resources