Explanation needed regarding JavaScript arrays and how they are being implemented [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have some JavaScript written by someone else and I'm trying to figure our exactly where some values are coming from, how they are formatted and what is being done with them. The values in question are citNumFirst, dateFirst, cdValues and cnValues.
This JavaScript is used to recursively open form fields for numbers and dates, then make an Ajax request (I think), but the Ajax data doesn't make any sense (value is: data: "countCitNum=" + countCitNum,)
Here is the code I need help with. Again, I'm trying to figure out where these values citNumFirst, dateFirst, cdValues and cnValues are coming from as these are what are being sent through the form submission (according to Fiddler).
My thinking is that this can all be done more efficiently with PHP, but I'm curious if the Ajax is even doing anything here, and if not are the values "cdValues" and "cnValues" being send as Javascript Arrays, or objects using the input forms.
$(document).ready(function() {
var citArray = [];
var thisCount = 1;
varcountCitNum = -1;
var cnArray = [];
var citNum = '';
var cnFirst = '';
var cdArray = [];
var issueDate = '';
$("#cnValues").val(cnArray);
$("#cdValues").val(cdArray);
function addCitNumber(){
var citNumField = document.getElementById("citNumFirst");
if(citNumField.value ==''){
var addfield_msg = "<span style='color:#F00;'>Please enter <br />Citation Number</span>";
$('#addfield_error').removeClass('hideCat');
$('#addfield_error').append(addfield_msg);
return false;
}else{
countCitNum++;
var addHTML = '';
var addDateHTML = ''
$.ajax({
type: "POST",
url: "/ci/ajaxCustom/addCitNum",
data: "countCitNum=" + countCitNum,
success: function(results){
if(results){
countCitNum = results;
}
addHTML = '<div id="newCitNum_'+countCitNum+'"><br /><strong>Citation Number:</strong><br /><input type="text" id="citNumInput_'+countCitNum+'" onchange="setCitNum(this,'+countCitNum+')"/></div>';
addDateHTML = '<div id="newDate_'+countCitNum+'"><br /><strong>Citation Issue Date:</strong><br /><input type="text" id="citDateInput_'+countCitNum+'" class="date" onchange="setIssueDate(this,'+countCitNum+')" readonly="readonly"/><img src="/euf/assets/themes/standard/images/delete_x.gif" width="29" height="23" border="0" class="imgDelete"/>Delete Citation Number</div>';
$('#anotherCitNum').append(addHTML);
$('#anotherCitDate').append(addDateHTML);
document.getElementById("#citDateInput_"+countCitNum);
$("#citDateInput_"+countCitNum).attr("disabled",true);
$(".date").datepicker();
}
});
}
data="";
}
*//******
Set Additional Citation Numbers and enable the date input
******/
function setCitNum(obj, countCitNum){
if(obj.value !='')
{
cnArray[countCitNum] = obj.value;
$("#cnValues").val(cnArray);
$("#citDateInput_"+countCitNum).removeAttr("disabled");
}else{
$('#citDateInput_'+countCitNum).val('');
$("#citDateInput_"+countCitNum).attr("disabled", true);
}
}
/******
Set Issue Date of additonal citations
******/
function setIssueDate(obj, countCitNum){
if(obj.value !=''){
cdArray[countCitNum] = obj.value;
}else{
cdArray[countCitNum] = '';
}
$("#cdValues").val(cdArray);
}
/******
Set Citation Number and enable date input unless Citation Number is blank
******/
function setFirstNum(obj){
cnFirst = obj.value;
$('#addLink').empty();
if(obj.value !='')
{
$("#citNumFirst").val(cnFirst);
$("#dateFirst").removeAttr("disabled");
$('#addfield_error').empty();
$('#addfield_error').addClass('hideCat');
var addLinkHTML = "<a href='javascript:void(0)' onclick='addCitNumber();'>Click here to add another Citation Number</a>"
$('#addLink').append(addLinkHTML);
}else{
$('#dateFirst').val('');
$("#dateFirst").attr("disabled", true);
}
}
/******
Set Issue Date of citation
******/
function setFirstDate(obj){
var issueDate = obj.value;
$("#dateFirst").val(issueDate);
}
Here is the associated HTML
<input type="hidden" name="cnValues" id="cnValues" />
<input type="hidden" name="cdValues" id="cdValues" />
<input type="text" id="citNumFirst" onblur="setFirstNum(this)" value=""/></div>
<div id="addfield_error" class="hideCat"></div>
</div>
<div id="anotherCitDate" style="float:left; padding-left:15px">
<input type="text" id="dateFirst" class="date" onchange="setFirstDate(this)" value="" readonly="readonly"/>

As far as I can tell, this is what's happening:
citNumFirst and dateFirst are the initial inputs. When citNumFirst input is changed (note: this definitely needs input validation), "Click here to add another" link appears. Clicking it will increment countCitNum, send that to the Ajax call, and if it's successful, display an additional set of date/number inputs which can be used to create a new citation number.
Ajax call: I'm not entirely sure what's going on here because what it's passing is the index of the input fields (countCitNum) that will be added (starting with zero and not counting the initial set). It's not passing the actual number or date, and it looks like it's expecting to receive that same index as results.
cnValues and cdValues store cnArray and cdArray, which are used to store the numbers and dates, respectively, of citations added using these newly created input fields. cnArray[0] corresponds to the value in input #newCitNum_0; cdArray[0] corresponds to #newDate_[0]. Any updates made to these input fields result in changes to the array, but I'm not seeing them being used anywhere in your code snippet (but since they are hidden inputs, they are probably being used after form submit).

Related

Send variable to $_POST without live search [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have modified a working live search script to include a combo box. I want the live search box to work as normal. I need the combo box when a selection is made to pass the selection in the form of a variable to the livecompsearch.php script. I don't want the combo box to search anything just to be able to use the variable if and when needed such as using $_POST['query2']. I have omitted much of the code from the php script as it is not really needed here, I only want to output the variable for now.
I am planning on using the dropdown as an option to search different columns in in a table by selecting one of the options first then to start typing what they are looking for in the live search box.
Testp.php
<div class="line">
<div class="box margin-bottom">
<div class="margin">
<div class="s-12 m-6 l-12">
<input type="text" name="search_box" id="search_box" class="searchbox" placeholder="Enter your live search here..." />
<select name="Search_Option" id="Search_Option" class="searchbox" style="width: auto;">
<?php
$options = array(
'0'=> 'All',
'1'=> 'Played',
'2'=> 'Scheduled',
'3'=> 'Cancelled'
);
$selected = 'Select';
foreach($options as $option=> $title){
if($selected==$option){
echo '<option value="'.htmlspecialchars($option).'" selected="selected">'.ucfirst($title).'</option>';
}else{
echo '<option value="'.htmlspecialchars($option).'">'.ucfirst($title).'</option>';
}
}
?>
</select>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
load_data(0);
load_data(1);
function load_data(page, query = '', query2 = '0')
{
$.ajax({
url:"includes/livecompsearch.php",
method:"POST",
data:{page:page, query:query, query2:query2},
success:function(data)
{
$('#dynamic_content').html(data);
}
});
}
$(document).on('click', '.page-link', function(){
var page = $(this).data('page_number');
var query = $('#search_box').val();
load_data(page, query);
});
$('#search_box').keyup(function(){
var query = $('#search_box').val();
load_data(1, query);
});
$('#Search_Option').change(function(){
var query2 = $('#Search_Option').val();
load_data(0, 1, query2);
});
});
</script>
livecompsearch.php
<?php
echo ' <p><strong>Variable: </strong>['.$_POST['query2'].']</p>';
?>
Hey so I might be misunderstanding your problem but I think you could either just use an if-statement so that if you only change the HTML if you get a certain result from the PHP.
Or better yet just don't have it fire if you change the combo-box.
Put the var query = $('#search_box').val() and var query2 = $('#Search_Option').val(); in the load_data function just before $.ajax({ then send it in that way.
Get rid of the query parameters obviously then just put the function call in your event handlers.
If you keep it all in one function then when it is triggered it will send the values of what the input is at that moment which I think is what you're going for.

Javascript/HTML How to remove element of javascript array dynamically through HTML input/text box [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 5 years ago.
The websites purpose is to store and order book titles, I need to make it so that the user can delete books they have entered into the array. I'm pretty new at Javascript but have a little bit of Java and C# experience.
Little bit stuck on this one. Was doing some reading about removing elements from the array within the code with splice and delete. But when i create a function for it, it removes everything in the array and not just the text box input string.
For the purposes of my assessment it needs to be done without using a third party library.
I'm aware that this is probably not the best way to go about storing data since it clears upon refresh or closing the page.
HTML:
<!DOCTYPE html>
<html>
<body>
<h1> Prototype Book Storage and Display </h1>
<form id = "formWrapper">
Search<br>
<input id="myTextBox" type="text" name="search">
<br>
<input onClick="submitData()" type="button" value="Submit Book">
<input onClick="printBooks()" type="button" value="Find Book">
<input onClick="deleteData()" type="button" value = "Delete Book">
<p id = "booktitle"></p>
</form>
</body>
</html>
Javascript:
var myFormData = []; //declare an array
var value1;
//Prints My Books to a list
function printBooks() {
clearBook();
alert(myFormData);
document.getElementById('booktitle').innerHTML = myFormData;
}
//Submits input to array
function submitData()
{
value1 = document.getElementById("myTextBox").value;
myFormData.push(value1);
alert(myFormData);
clearField();
}
//Deletes data from the array
function deleteData()
{
deleteValue = document.getElementById("myTextBox").value;
myFormData.splice(deleteValue);
alert(deleteValue + " " + "Deleting your book");
}
//clears textbox field
function clearField()
{
var txt2 = document.getElementById("myTextBox");
txt2.value = "";
}
//Refreshes book object model
function clearBook()
{
var txt3 = document.getElementById("booktitle");
txt3.value="";
}
The problem is in
myFormData.splice(deleteValue);
splice() expects a starting index, you are passing a string value. See How do I remove a particular element from an array in JavaScript? on how to use it.
In your case it would be
// get the index of the value in the array or -1 if it does not exist
var index = myFormData.indexOf(deleteValue);
// only try removing it, if it exists in the array
if (index !== -1) {
myFormData.splice(index, 1);
}

JS: name of last input element (HTML/PHP) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I better make a list in order to explain the steps that I would like to do:
Get the name of the last element of the html-input (has been generated via PHP)
The basic setting looks like this:
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
Pass it over to a JS function
Append some additional fields (use part of the name as an id for new fields
The JS-script works fine and I am able to add fields. Also the content of the fields is being processed by the PHP script and written in a db.
Short: how do I get the last value, no matter how many fields there are?
edit: I had forgotten that there is a submit button that would appear as the last element as well ... sorry for that
There are a number of approaches, but given all other answers rely on the jQuery library (which adds an unnecessary overhead), I'll focus on showing some plain JavaScript approaches (works on recents browsers above IE8+).
var allTextInputs = document.querySelectorAll('input[type="text"]'),
lastInput = allTextInputs[allTextInputs.length - 1],
lastInputName = lastInput.name;
var allInputsTxt = document.querySelectorAll('input[type="text"]');
var lastInput = allInputsTxt[allInputsTxt.length - 1];
var lastInputName = lastInput.name;
var lastInputValue = lastInput.value;
alert('last input name : ' + lastInputName + '; last input value : ' + lastInputValue);
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
If what you want is the value and not the name attribute, do this after using the same approach as above to get the name of the last <input type="text"/>:
var lastInputValue = lastInput.value;
These approaches will give the value of the last <input /> of the type="text" in the document at the point at which the code is run; to find the value of a last <input /> that's dynamically added to the document, you'll need to re-run a working approach following that element's insertion.
jQuery...
var lastInputName = $('input[type="text"]:last').attr('name');
The following jQuery code should do the trick.
var lastValue = $("input[type=text]:last").val();
Also with jQuery:
var $inputs = $("input[type=text]");
var lastValue = $inputs[$inputs.length - 1].value;
Use CSS3 selectors in combination with sizzle (jquery) to target last element
var name = $('input[name^=E_]:last')[0].name
the last value in PHP or JavaScript?
in PHP the fields are normally passed as an array, so you can get the last value using
end($array)
Even better if you name your filed like this
<input type='text'name='E[8]' value= '123' />
<input type='text'name='E[9]' value= '456' />
<input type='text'name='E[10]' value= '789' />
in JS you need to get the fields into an array and get the last.... you need something like this
var myFields = document.forms["myform"].getElementsByTagName('input'),
var lastValue = myFields[(myFields.length-1)].value;
By wrapping your code a parent element, let's says with an attribute id="inputs", here is a vanilla DOM (no jQuery) solution :
// start by finding the last-most element
var lastInput = document.getElementById('inputs').lastElementChild;
// search backward to the last 'text' element
while (lastInput && lastInput.type !== 'text') {
lastInput = lastInput.previousElementSibling;
}
// and get its value
var lastValue = lastInput ? lastInput.value : null;
The interesting part of this solution is that is create no array, so you save some JavaScript memory.
It should be ok with Firefox, Chrome and IE 9.

Getting multiple selected checkbox values in a string in javascript and PHP

I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascript variable. How can I do this?
<!-- Javascript -->
<script>
function getLoc(){
var all_location_id = document.getElementByName("location[]").value;
var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 -->
}
<script>
foreach($cityrows as $cityrow){
echo '<input type="checkbox" name="location[]" value="'.$cityrow['location_id'].'" />'.$cityrow['location'];
echo '<br>';
}
echo '<input name="searchDonor" type="button" class="button" value="Search Donor" onclick="getLoc()" />';
var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
This is a variation to get all checked checkboxes in all_location_id without using an "if" statement
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
I you are using jQuery you can put the checkboxes in a form and then use something like this:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>

Javascript is working fine but not in jQuery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This code works fine for me in Javascript.
function check_u() {
var errormessage = document.getElementById("errorname");
var user = document.forms["login"]["user"].value;
if (user == null || user == "") {
errormessage.innerHTML = "Please enter your user id";
} else {
errormessage.innerHTML = "";
}
}
function check_p() {
var errormessage = document.getElementById("errorpass");
var pass = document.forms["login"]["password"].value;
if (pass == null || pass == "") {
errorShow.innerHTML = "Password cannot be blank";
} else {
errorShow.innerHTML = "";
}
}
My html is :
<input type="text" name="user" autocomplete="off" onBlur="check_u()" />
<input type="text" name="password" autocomplete="off" onBlur="check_p()" />
<div id="errorname" />
I have written an alternative for this code in jQuery. In JavaScript it works fine but in jQuery when I don't enter any input first time it is showing error message. I enter some value to it then it clears the error message. Now if I am leaving the input blank the error message doen't show up. Here is my jQuery code:
function check_u(){
var fieldValue = $("input[name=user]").val();
if(fieldValue==""||fieldValue==null){
$("#errorname").html('<div id = "error_left"></div>'+
'<div id = "error_right"><p>This is a required field</p></div>');
}else{
$("#errorname").hide();
}
}
Why, if on repeated calls, does my errorname div not show up?
Does .hide() do more than just clear out the div?
In the javascript else clause, you are clearing the contents, but in the jQuery clause you are hiding the entire error element.
Instead of
$("#errorname").hide()
try
$("#errorname").html("")
You need to show errorname after setting the html
$("#errorname").html('<div id = "error_left"></div>'+
'<div id = "error_right"><p>This is a required field</p></div>').show();
You are hiding the errorname div in case of a valid entry, then if value becomes invalid then you need to set the error message and set the visibility to of the div.
demo: Plunker
Your onblur is calling check_u() but your other jQuery example's function name is checkUser()

Categories