get href from php and use element in JQuery - javascript

I have xyz.php and working menu <li> elements. I need to get hreffrom php use it in Java script for navigate away. So I have list of li tag and in code it's displaying one for example. Each li tag has unique href.
My question is: If I have select only one li elements from the list. I want to use that li's associated href in IF condition in JavaScript and ELSE part is multiple Li's selected. The code is working for else part. But, I am having issue with IF part.
I am not getting the href value from PHP. you can get 'href'from $xyz['url'] in php.
xyz.php
<div class="global-wrapper">
<ul class="list">
<li>
<input id="retreat-<?php echo $xyz['api_id']; ?>" class="custom-check-input more-filter-experience" type="checkbox" value="<?php echo $xyz['name']; ?>" data-home-location="<?php echo $xyz['api_id']; ?>">
<label class="custom-check-label" for="retreat-<?php echo $xyz['api_id']; ?>"></label>
</li>
</ul>
</div>
Here, the java script code:
xyz.js
if(retreatIdArray.length === 1 && exploreDate === undefined) {
var categoryId = $('.global-wrapper').find('.loadProducts').attr('data-categoryid');;
window.location.href = "/categoryId"; // having issue
} else{
window.location.href = '/destination';
}

You wrote undefine instead of undefined. The statement inside if will never be true.
Also, to check for undefined, it's better to use typeof.
if(retreatIdArray.length === 1 && typeof exploreDate == 'undefined') {
retreats = $('.global_wrapper').find('.custom-check-input').val();
window.location.href = '/href';
} else {
window.location.href = '/destination';
}
Note: untested code, you may have to adjust it to your needs. Please let me know if it works.

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);
});
}
});

PHP doesn't see new elements created with jQuery and AJAX

I faced an issue since I can't get a just created element with a PHP script.
I have a list of tags loaded with PHP:
<ul>
<li>
<input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="4">
Some tag
<li>
<ul>
Thanks to AJAX I append another element inside the UL
jQuery(document).ready(function($) {
$('.add-tag-btn').click(function(event) {
var tag_title = $('.tag-search').val();
$.ajax({
url: 'add-tag.php',
type: 'POST',
dataType: 'json',
data: {
'tag_title': tag_title
},
success:function(result){
$('.tag-search').val('');
$('.new-tags').append('<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="'+result.tag_id+'">'+tag_title+'</li>');
console.log(result.tag_id);
}
});
});
});
Thus I have a new UL
<ul>
<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="4">Value #4</li>
<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="5">Value #5 (new value generated with jQuery and AJAX)</li>
</ul>
But once I submit the form, only the existed value is added to DB.
if (isset($_POST['submit'])) {
....
bla bla bla
foreach ($_POST['check_list_tags'] as $value) {
$arr2[] = $value;
}
bla bla bal
}
Looks like that PHP can't handle a new value without the page reloaded. At the same time, I add
checked="checked"
dynamically and that works just perfect.
Can anyone explain me how to force PHP to see the newly created elements (the elements that were appended to the existed HTML by the means of jQuery).
Thanks everyone for the assistance.
upd:
This is how I add the "checked"
jQuery(document).ready(function($) {
$('.adm-checkbox').click(function(event) {
if (this.checked) {
this.setAttribute("checked", "checked");
console.log('checked');
} else {
this.removeAttribute("checked");
}
});
});
This is how the form looks like:
<form class="" action="<?php echo $router->url ?>" method="post" enctype="multipart/form-data">
.....
<ul class="new-tags">
</ul>
<ul>
<?php foreach ($admin->getAdmTags() as $value): ?>
<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="<?php echo $value['id'] ?>"><?php echo $value['title'] ?></li>
<?php endforeach; ?>
<ul>
</form>
UPD # 2:
May be the reason is that I use two separate functions in jQuery for "checked"??!?!
$('.adm-checkbox').click(function(event) {
if (this.checked) {
this.setAttribute("checked", "checked");
console.log('checked');
} else {
this.removeAttribute("checked");
}
});
and
$('.adm-tags').on('click', '.adm-checkbox', function(event) {
if (this.checked) {
this.setAttribute("checked", "checked");
console.log('checked');
} else {
this.removeAttribute("checked");
}
});
I do it because onclick doesn't work for the newly created elements.
P.s: It doesn't matter where I put a newly created "li"...
Thank everyone for participation. I've created a new page and did everything again. And now it works. Now I need to find the mistake in my full code.
Name attributes can be arrays so the name isn't the issue - HTML input arrays
I think the reason is as you mentioned, the checked attribute needs to be added to all of the inputs otherwise the value won't be sent in the request.
If the inputs were text or number for example, then the checked attribute wouldn't be needed.
The same would apply to radio inputs, or the selected attribute for a select menu.
TLDR, add checked:
$('.new-tags').append('<li><input class="adm-checkbox" type="checkbox" name="check_list_tags[]" value="'+result.tag_id+'" checked>'+tag_title+'</li>');
That is of course, if it should be automatically checked and not reliant on the user checking it manually.
I may have to change this answer based on if this is a traditional form submission or an ajax submission not using a form.
I don't know how to close the topic. It works with the newly created code. Once I find out the mistake in my full code, I will reply with the explanation of my mistake.
When you send a form though either POST or GET every input needs a unique name. From you code it looks like you add a new input element with a name attribute that has the same value as the already existing element.
I suspect if you add the new element with a unique name value it should work. You could incorporate that into you JavaScript code by having a counter for the number of input elements with name X and then add a number. And you would need to do a similar thing in your PHP.
Edit: Apparently you can have name attributes with the same name if you use '[]' after the name, thank you #martincarlin87

Get attribute from many divs to toggle class

So I am trying to check a bunch of divs on an inbox page and I am returning an array from an AJAX call to know which divs to change the font-style of. To achieve this, I have to first check their data-value attribute and then add/remove a class(bold vs. normal fro read/unread messages). The problem is that when I refer to the messageDiv object, it toggles all the messages on the page. Looping through the messages makes the most sense to me, but I do not know how to store a div an array to achieve this.
data['messages']=[3,5,8,9]
var messageDiv=$('.widget .inbox-row');
if (data['status']=='A'){//read
if ($.inArray(messageDiv.data('value'),data['messages']) && messageDiv.hasClass('unread-msg')) {
messageDiv.removeClass('unread-msg').addClass('read-msg');
}
}
if (data['status']=='N'){//unread
if ($.inArray(messageDiv.data('value'),data['messages']) && messageDiv.hasClass('read-msg')) {
messageDiv.removeClass('read-msg').addClass('unread-msg');
}
}
This is what a message looks like, iterated many times on the page:
<div class="<?php echo $message_read_status; ?> inbox-row" data-value="<?php echo $messageid; ?>" >
<?php echo $body; ?>
</div>
Sincere thanks for any help. Sorry if this is a pretty specific question. I tried to make it as non-specific as possible.
The problem is e is a set of elements, so when you say messageDiv.data('value'), it will return teh data-value of the first element in the set.
You need to iterate over each item in the array and run the conditions against each one
var messageDiv = $('.widget .inbox-row');
messageDiv.each(function () {
var $this = $(this);
if (data['status'] == 'A') { //read
if ($.inArray($this.data('value'), data['messages']) > -1 && $this.hasClass('unread-msg')) {
$this.removeClass('unread-msg').addClass('read-msg');
}
} else if (data['status'] == 'N') { //unread
if ($.inArray($this.data('value'), data['messages']) > -1 && $this.hasClass('read-msg')) {
$this.removeClass('read-msg').addClass('unread-msg');
}
}
})

why after the 3rd click my function doesn't work?

I have the following html code:
<?php foreach ($this->tags as $uri=>$tag){?>
<input type="checkbox" name="tags[]" style="display: none;" value="<?php echo $uri;?>" id="create_<?php echo $uri;?>" <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'checked="checked"':'';?> />
<span onclick="selectTag(this.id)" id="create_<?php echo $uri;?>" for="create_<?php echo $uri;?>" class="tag <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'selected':'';?>"><?php echo str_replace(' ', ' ', $tag);?></span>
<?php }?>
And here is my JS code:
function selectTag(id) {
var input = '.tags input#'+id;
var span = '.tags span#'+id;
if ($(input).is(':checked') && $(span).hasClass('selected')) {
$(span).removeClass('selected');
$(input).attr('checked', false);
}
else {
$(span).addClass('selected');
$(input).attr('checked', true);
}
}
When I click on a span box, selects the box, and when I click again on it, it unselects it. The problem is, that after the 3rd time, it just stops working.
What is wrong with my code that is not working?
JQuery now has a prop method that is a slightly better alternative to using the attr method.
Try replacing your calls with attr("checked", true); with calls to prop("checked", true);
See here for documentation on prop: http://api.jquery.com/prop/
Here for a discussion between the two: .prop() vs .attr()
Edit:
Also, as Ed Cottrell stated, you'll want to have UNIQUE id attributes for all your elements on your page.
Edit2:
I have created a fiddle that demonstrates this usage: http://jsfiddle.net/xDaevax/E39hc/
You are giving the input and the span the same id attribute. Ids must be unique per element; you cannot have an input and a span the same id. Doing it this way will cause all sorts of problems, including the behavior you are experiencing. Give one of them a slightly different id (like create_<?php echo $uri;?>_span).
Also, as #xDaevax says, you should use .prop rather than .attr -- I have had the same problem when using .attr.

Pass checkbox value to Edit (using href)

I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.
My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:
... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
<tr><td><input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>"
value="<?php echo $row['docid'];?>"></td> ...
I have an EDIT Link as a menu in the top in view.php.
<a href="editdoc.php>Document</a>
My question : How do I pass the value of the checked checkbox when I click the edit link.
Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.
Thanks in advance.
Lakshmi
Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.
I found a solution!!!
Though I did it in a different way, I thank Jaak Kütt for all the support and helping me to think of a possible way..
This is what I did.. I named the form as showForm and moved to editdoc.php through the function itself.
My Check Box :
<form name="showForm">
<input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>" value="<? php echo $row['docid'];?>">
My Link:
<a id="a_editdoc" onclick="getchkVal();" title="Edit Document">Document</a>
The corresponding script:
<script>
function getchkVal() {
var contents, vals = [], mydocid = document.forms['showForm']['chk_docid[]'];
for(var i=0,elm;elm = mydocid[i];i++) {
if(elm.checked) {
vals.push(encodeURIComponent(elm.value));
}
}
contents = vals.join(',');
window.location="editdoc.php"+"?v="+contents;
}
</script>
In the editdoc.php :
<?php
$cval=$_GET['v'];
?>
Thanks.
make sure your inputs have different id-s..
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
...<input type="checkbox" name="chk_docid[]" class="chk_input"
id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
using jQuery:
Document
$("#editdoc").click(function(){
var selection=$("input.chk_input:checked");
if(selection.length){
var href=$(this).attr('href')+'?'+selection.serialize();
$(this).attr('href',href);
}
return true;
});
non-jQuery:
<a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
function submitWithChecked(e,className){
// fetch all input elements, styled for older browsers
var elems=document.getElementsByTagName('input');
for (var i = 0; i < elems.length; ++i) {
// for each input look at only the ones with the class you are intrested in
if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
// check if you need to add ? or & infront of a query part
e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
// append elements name and value to the query
e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
}
}
return true;
}
in editdoc.php fetch the values with php using $_GET['name_of_input_element']

Categories

Resources