Save input value onclick div - javascript

Next to a input I want to display two div's with plus and minus signs, so that when clicking on one of the divs, the value insdie the input increase or decrease.
It almost works perfect, but the best way to save the input. Is by changing the input and than load the /save url. The input works perfect with this code, that on changing the /save url loads and the value is saved.
I want the same for the div's, that when clicking on the div the value inside the input changes and the value is saved by the /save URL.
How do I need to change my code for this?
CODE HTML:
<div class="quote-item product-quote-qty">
<div id="qdiv_<?php echo $item->getId() ?>" nowrap="nowrap" class="qty-div input-box">
<div class="reduced items item-<?php echo $item->getQty()*1; ?>" onclick="var result_<?php echo $item->getId() ?> = document.getElementById('qty_<?php echo $item->getId() ?>'); var qty_<?php echo $item->getId() ?> = result_<?php echo $item->getId() ?>.value; if( !isNaN( qty_<?php echo $item->getId() ?> ) && qty_<?php echo $item->getId() ?> > 1 ) result_<?php echo $item->getId() ?>.value--;saveForm();return false;">-</div>
<input type="text" name="quote_request[<?php echo $item->getId() ?>][qty][]" id="qty_<?php echo $item->getId() ?>" value="<?php echo $item->getQty()*1; ?>" size="4" title="<?php echo $this->__('Qty') ?>" onchange="location.href='save'" class="required-entry validate-zero-or-greater input-text" maxlength="12" />
<div class="increase items" onclick="var result_<?php echo $item->getId() ?> = document.getElementById('qty_<?php echo $item->getId() ?>'); var qty_<?php echo $item->getId() ?> = result_<?php echo $item->getId() ?>.value; if( !isNaN( qty_<?php echo $item->getId() ?> )) result_<?php echo $item->getId() ?>.value++;saveForm();return false;">+</div>
</div>
</div>
CODE JS:
function saveForm() {
var form = $('quotelist').clone(true);
//update textarea
var i = 0;
$('quotelist').select('textarea').each(function (el) {
form.select('textarea')[i].value = $(el).value;
i++;
});
var action = $('quotelist').action;
action = action.replace("quoteRequest", "save");
form.action = action;
form.request({
onComplete: function(){ Miniquote.reloadContent(); }
});
}
function addQtyFieldSaver(){
$$('#shopping-cart-table input[type=text]').each(function (el) {
return $(el).observe('blur', function(e){
saveForm();
});
});
}
EDIT:
function addQtyFieldSaver(){
$$('#shopping-cart-table input[type=text]').each(function (el) {
return $(el).observe('blur', function(e){
saveForm();
});
});
$('.reduced').click(function () {
var el = $(this).parent().find('input:text');
var newval = (parseInt($(el).val(),10) - 1 > 0)?$(el).val() - 1:0;
el.val(newval);
saveForm();
});
$('.increase').click(function () {
var el = $(this).parent().find('input:text');
var newval = parseInt($(el).val(),10)+1;
el.val(newval);
saveForm();
});
}

Get rid of your PHP code in your plus and minus divs like this
<div class="reduced items">-</div>
<div class="increase items" >+</div>
And add this to your addQtyFieldSaver function
$('.reduced').click(function () {
var el = $(this).parent().find('input:text');
var newval = (parseInt($(el).val(),10) - 1 > 0)?$(el).val() - 1:0;
el.val(newval);
saveForm();
});
$('.increase').click(function () {
var el = $(this).parent().find('input:text');
var newval = parseInt($(el).val(),10)+1;
el.val(newval);
saveForm();
});
With this solution, the click event on the +/- divs accesses the input text field using its parent container in order to get the quantity of the input value and change it. Then calls the function saveForm() to save the new data.
EDIT: Full Example
function saveForm() {
alert('saveform is called');
}
function addQtyFieldSaver(){
$('#shopping-cart-table input[type=text]').each(function (el) {
return $(el).bind('blur', function(e){
saveForm();
});
});
}
$(document).ready(function(){
addQtyFieldSaver();
$('.reduced').click(function () {
var el = $(this).parent().find('input:text');
var newval = (parseInt($(el).val(),10) - 1 > 0)?$(el).val() - 1:0;
el.val(newval);
saveForm();
});
$('.increase').click(function () {
var el = $(this).parent().find('input:text');
var newval = parseInt($(el).val(),10)+1;
el.val(newval);
saveForm();
});
})
<html>
<head>
<title>Ejemplo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="shopping-cart-table">
<div class="quote-item product-quote-qty">
<div id="qdiv_1" nowrap="nowrap" class="qty-div input-box">
<div class="reduced items">-</div>
<input type="text" name="quote_request[1][qty][]" id="qty_1" value="1" size="4" title="1" onchange="location.href='save'" class="required-entry validate-zero-or-greater input-text" maxlength="12" />
<div class="increase items" >+</div>
</div>
</div>
</div>
</body>
</html>

Related

manipulate dynamic input with php mysql and js

I have a table named description:
CREATE TABLE description(
word_id int(11),
word varchar (50),
PRIMARY KEY (word_id)
);
and I try to get all word in this table and for every word I create a checkbox with value and id equal at a value of the word that I get from table description,
if the checkbox is checked, I save his value in var abcd.
<?php
///connection
$get_word = $bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<br>
<script>
$('#<?php $donnees["word"] ?>').on('change', function() {
var abcd= this.checked ? this.value : '';
});
</script>
<?php
}
?>
Now, I want to create a button out of boocle while , if this button is clicked,it must give me the value of checkbox checked.
Here's how you could do it using jQuery. As you already have the PHP logic, my example demonstrates the jQuery code only:
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
console.log($(el).val())
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="Item 1">Item 1
<input type="checkbox" value="Item 2">Item 2
<input type="checkbox" value="Item 3">Item 3
<button id="getCheckedBoxes">Get checked boxes</button>
hope this will solve your problem
PHP code
<?php
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
JS CODE
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
var check_val = document.getElementById('myid_'+word).value;
alert(check_val);
}
}
</script>
or you can do this
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
alert(word);
}
}
</script>
add class name such as clickable to your input tag.
after all rendering in php add script that runs when any input with clickable class changed and you can get that tag!
<?php
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) { ?>
<input class="clickable" type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<?php } ?>
<script>
$('.clickable').on('change', function(item) {
console.log(item)
});
</script>
I try this
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<label><?php echo $donnees["word"] ?></label>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
<button id="getCheckedBoxes">Get checked boxes</button>
<script type="text/javascript">
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
alert($(el).val()) ;
})
})
})
</script>
And the alert message is empty,it don't show the value of checkbox chekced

Hide and Display activity checkbox when click on services checkbox

PHP
<?php
//for service 1
$all_activities = "select * from activity join displayserviceactivitymap on activity.activity_id = displayserviceactivitymap.activity_id right join services on services.service_id = displayserviceactivitymap.service_id";
$all_activities = $conn->query($all_activities) or die ($conn>error.__LINE__);
$activities = [];
while ($row = $all_activities->fetch_assoc()) {
$activities[] = $row;
}
$repeated = 'repeated';
foreach ($activities as $act) {
if($act['servicename'] != $repeated){
echo '<br><input type="checkbox" name="arr['.$act['service_id'].'][service]" value="'.$act['service_id'].'" id="'.$act['service_id'].'">'.$act['service_id'].$act['servicename'].'<br>';
$repeated = $act['servicename'];
}
if($act['activity_id'] != '')
echo '<input type="checkbox" name="arr['.$act['service_id'].'][activity][]" value="'.$act['activity_id'].'" id="'.$act['activity_id'].'">'.$act['nameofactivity'].'<br>';
}
?>
Output of My code is
Incometax
Return
filling
GST
Form
Return
GSTR
TDS
Application
Refund
Here Incometax,GST,TDS are services and others are related activity of the services.
I want to display activity when I check checkbox and hide when I uncheck checkbox.
Please try to run this whole code for better understand
<?php
function array_group(array $data, $by_column) {
$result = [];
foreach ($data as $item) {
$column = $item[$by_column];
unset($item[$by_column]);
if (isset($result[$column])) {
$result[$column][] = $item;
} else {
$result[$column] = array($item);
}
}
return $result;
}
$activities = array(
array('service_id' => '1',
'servicename' => 'Incometax',
'activity_id' => '1',
'nameofactivity' => 'Return'),
array('service_id' => '1',
'servicename' => 'Incometax',
'activity_id' => '2',
'nameofactivity' => 'filling')
);
$activities = array_group($activities, 'servicename');
?>
<link href = "https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel = "stylesheet" />
<script src = "https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<?php foreach ($activities as $key => $act) { ?>
<div id="accordion">
<h3>
<label for='product-44-44'>
<input type='checkbox' name="arr[<?php echo $act[0]['service_id']; ?>][service]" value="<?php echo $act[0]['service_id']; ?>" id="<?php echo $act[0]['service_id']; ?>"/>
<?php echo $key; ?>
</label>
</h3>
<div class="columns">
<?php foreach ($act as $value) { ?>
<div class="d1">
<label>
<input type="checkbox" name="arr[<?php echo $value['service_id']; ?>][activity][]" value="<?php echo $value['activity_id']; ?>" id="<?php echo $value['activity_id']; ?>">
<?php echo $value['nameofactivity']; ?>
</label>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<script>
$("#accordion")
.accordion({
collapsible: true,
active: false,
heightStyle: "content",
beforeActivate: function (event, ui) {
var oldInput = ui.oldHeader.find('input');
oldInput.prop('checked', !oldInput.prop('checked')) // this bit unchecks when the accordion is closed
var newInput = ui.newHeader.find('input');
// this bit checks when the accordion is opened
newInput.prop('checked', !newInput.prop('checked'))
}
}
);
</script>

hide div from div when there is no search result

I've tried so many methods from stackoverflow and other websites but whenever i succeed in hiding the div. No search result is displayed at all.
I've tried the :empty selector and fiddling around with the php code and js code. but since i'm very new to this i just can't seem to crack the error. What am i doing wrong?
My HTML
<div class='search'>
<form class="searchbox" action='index.php' method='post' autocomplete='off'>
<input type='text' name='search' class='searchform' placeholder='Søg efter skole...' onkeyup="searchq();">
</form>
<div id="output"></div>
</div>
PHP
<?php
include("connection.php");
$output = '';
//collect
if(isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^a-zA-Z0-9æøå]#i"," ", $searchq);
$query = mysqli_query($mysqli, "SELECT * FROM `products` WHERE name LIKE '%$searchq%'") or die("could not search");
$count = mysqli_num_rows($query);
if($_POST['searchVal'] == NULL) {
$output = '';
} else {
while($row = mysqli_fetch_array($query)) {
$name = $row['name'];
$id = $row['id'];
$output .= ''.$name.'<br>';
}
}
}
echo "<div class='output'>$output</div>";
?>
And JS
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("search.php", {
searchVal: searchTxt
}, function(output) {
$("#output").html(output);
});
}
HTML
<div class='search'>
<form class="searchbox" action='index.php' method='post' autocomplete='off'>
<input type='text' name='search' class='searchform' placeholder='Søg efter skole...' onkeyup="searchq();">
</form>
<div id="output" style="display: none;"></div>
</div>
PHP
.....
echo $output;
JS
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("search.php", {
searchVal: searchTxt
}, function(output) {
$("#output").html(output);
if(output.length > 0) {
$("#output").show();
}
});
}

PHP update div after click submit

I am trying to do update "refresh" div after click Submit button and also every 5 seconds. I checked some questions, but I could not find what I was looking for.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
echo '<div id="refresh">';
while ($r = $q->fetch()):
echo 'Sender: ';
if($r['senderid'] == $a) {echo $query1['username'];}
elseif($r['senderid'] == $b) {echo $query2['username'];}
echo '</br>';
echo $r['message'];
echo '</br></br>';
endwhile;
echo '</div>';
?>
<form method="post">
<input type="hidden" name="a" value="<?php echo $a;?>">
<input type="hidden" name="b" value="<?php echo $b;?>">
<textarea name="message" rows="3" cols="30"></textarea><br><br>
<input id="submit" type="submit" value="Submit" />
</form>
<script>
$(document).ready( function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
$.post("submit.php", $("form").serialize()); // Post the data
$('textarea[name=message]').val('')
});
});
</script>
Please make some rudimentary investigation on $.post and setTimeout
Here is an example - there are a few questions you need to consider
var val = "";
function refreshDiv() {
var $text = $('textarea[name=message]');
val = $text.val() || val; // what to do if user clears the field?
if (val == "") return; // stop if nothing there
$.post("submit.php", $("form").serialize(),function(data) {
$("#refresh").html(data)); // show the data
setTimout(refreshDiv,5000); // call it again in 5 secs
// $text.val(''); // not sure about this...
});
}
$(function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
refreshDiv();
});
});

Concatenate variable into radio button selector

I am trying to find the value of a checked radio button. I am concatenating the variable 'flagName' into the input selector, and it keeps returning undefined. Here is my JQuery:
function filterProjects (searchInput) {
var filter = $(searchInput).val(), count = 0;
var $projects = $(".ProjectDisplay");
$projects.show();
$projects.each(function () {
var $currentProject = $(this);
var projectFlags = $(this).data();
for (var flagName in projectFlags) {
var flagValue = projectFlags[flagName];
var checkedInputValue = $("input[name='" + flagName + "']:checked", "#flagSearchForm").val();
if ((checkedInputValue == "yes" && flagValue == "0") || (checkedInputValue == "no" && flagValue == "1")) {
$currentProject.hide();
}
}
if ($(this).find(".projectName").text().search(new RegExp(filter, "i")) < 0) {
$(this).hide();
}
});
}
I am trying to find the value of checkedInputValue. flagName and flagValue both return what they are supposed to. In the HTML, I have a form that loops through a PHP array to create multiple fieldsets that have three radio buttons each. Here is part of my HTML where the form is:
<form id="flagSearchForm" name="flagForm">
<div class="grid-unit grid-unit-9-14">
<h4>Search by Flag Value</h4>
<div class="flagSearch">
<div class="wrapper grids">
<?php
$flag_names = array("hasBib", "hasChoice", "hasEbooks", "hasFrbr", "hasLcd","hasLtp", "hasNlm", "hasPeers", "includeDewey", "includeGovtDocs", "includeNonBooks", "includeOpacUrl", "includeProtection", "includeScores"); ?>
<?php foreach ($flag_names as $i=>$flag_name):
?>
<div class="flagfields">
<div class="grid-unit grid-unit-3-14">
<fieldset>
<span class="flagName"><?php echo $flag_name; ?></span>
<input type="button" value="N/A" class="tri-state ignore" id="<?php echo $flag_name; ?>"/>
<input type="radio" name="<?php echo $flag_name; ?>" value="ignore" id="<?php echo $flag_name; ?>-ignore" class="radio-button" checked><label for="<?php echo $flag_name; ?>-ignore">Ignore</label>
<input type="radio" name="<?php echo $flag_name; ?>" value="yes" id="<?php echo $flag_name; ?>-yes" class="radio-button"><label for="<?php echo $flag_name; ?>-yes">Yes</label>
<input type="radio" name="<?php echo $flag_name; ?>" value="no" id="<?php echo $flag_name; ?>-no" class="radio-button"><label for="<?php echo $flag_name; ?>-no">No</label>
</fieldset>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<input type="submit" value="submit" class="flagSearchSubmit">
</div>
Is my syntax for checkedInputValue wrong?
I'm not sure what your filter/regex was so that will need to be completed. This logs all the selected inputs.
Here is a fiddle: https://jsfiddle.net/c4qbywrt/7/
function filterProjects(searchInput) {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var $currentProject = $(this);
var checkedInputValue = $(this).val();
var flagValue = '0'; // Not sure what is setting this
if ((checkedInputValue == "yes" && flagValue == "0") || (checkedInputValue == "no" && flagValue == "1")) {
$currentProject.hide();
}
var filter = '';
if ($(this).find(".projectName").text().search(new RegExp(filter, "i")) < 0) {
$(this).hide();
}
}
});
}
$("#searchProjects").keyup(function () {
filterProjects($(this));
});
$("#flagSearchForm").submit(function (event) {
event.preventDefault();
filterProjects($("#searchProjects"));
});

Categories