JS filter/autocomplete - javascript

I'm trying to get a search field on my site to have an autocomplete/filter function based off of strings in a JSON object. I want to treat the search box as a way to filter out anything that could be in the JSON object.
Here's the search bar in html:
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
And here's the JS for the JSON object, created from a php array:
<script type = "text/javascript">
var orderFormData = <?php Json_encode ($tempdata);?>;
</script>
I'm not sure the best function to use or how to use it on the JSON object, but I've heard JS autocomplete may be a good solution.
Is there a pretty straightforward way to tie these together and have a nice autocomplete/filter function on my search?

This is just given as a proof-of-concept:
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
<script>
var orderFormData = <?php Json_encode ($tempdata);?>;
</script>
<script>
var orderData = orderFormData // default value
var search = function (e) {
var term = e.currentTarget.value
orderData = Object.entries(orderFormData).reduce(function (data, entry) {
if (entry[0].match(term) || entry[1].match(term)) {
data[entry[0]] = entry[1]
}
return data
}, {})
console.log(orderData)
}
document.querySelector('#srch-term').addEventListener('keyup', search)
</script>
This handles the filter part, based on the a match from key/value to the term given in the input.
If you want the autocomplete, then you will have to code much more :)

You forgot to add echo:
<?php echo json_encode($tempdata);?>;
When you are using json_encode, you need to echo or print(). Also make sure you use the right case (optional).

Related

javascript + flask - Proper way passing an json array to server via post request?

I have to pass an json array to the server use post request:
<form action="../../../submit/" method='post' style="margin-top:-10px" id="submitBox">
<input class="attr" type="text" name="task_url" value= "annotate/{{task_name}}/{{taskid}}/{{frame_idx+1}}" hidden>
<input class="attr" type="text" name="frame_id" value= "{{frame.id}}" hidden>
<input class="attr" type="text" name="boxes_info" value = "" hidden id="boxes_info">
<button class="btn btn-default" id="submit" class="attr_sub">
<span class="glyphicon glyphicon-ok-circle"></span>
Submit
</button>
</form>
and here is how I create an json array and pass it to input value
d3.select('#submit').on('click', function(){
var boxes = [];
var box = {};
d3.selectAll('rect').each(function(){
var rect = d3.select(this)
box['xmin'] = rect.attr('x');
box['ymin'] = rect.attr('y');
box['width'] = rect.attr('width');
box['height'] = rect.attr('height');
box['label'] = rect.attr('class');
boxes.push(JSON.stringify(box));
})
boxes = JSON.stringify(boxes);
d3.select('#boxes_info').attr('value',boxes);
})
on the server side I get the the form data:
bboxes = request.form["boxes_info"]
bboxes = json.loads(bboxes)
print bboxes[0]['xmin'] // error: string indices must be integers
print bboxes[0][0] // return '{'
print bboxes
//[u'{"xmin":"433.9936102236422","ymin":"4.8","width":"404.2108626198083","height":"461.96","label":"person"}', u'{"xmin":"433.9936102236422","ymin":"-18.2","width":"404.2108626198083","height":"20","label":"person"}', u'{"xmin":"490.73482428115017","ymin":"291.84","width":"286.517571884984","height":"197.44","label":"handbag"}', u'{"xmin":"490.73482428115017","ymin":"268.84","width":"286.517571884984","height":"20","label":"handbag"}']
It seems like I have to json.loads('bboxes[0]') again. I think I make something wrong in my code. Can anyone tell me what is the proper way to do so?
It looks like you do JSON.stringify twice on client, that's why you need to do json.loads on the server twice.
Your code (simplified):
d3.select('#submit').on('click', function(){
d3.selectAll('rect').each(function(){
...
boxes.push(JSON.stringify(box)); // stringify each box
})
boxes = JSON.stringify(boxes); // stringify array with stringified boxes
})
Instead, try to use stringify once, on the resulting array:
d3.select('#submit').on('click', function(){
d3.selectAll('rect').each(function(){
...
boxes.push(box); // don't stringify heare
})
boxes = JSON.stringify(boxes); // stringify the array
})

How can I change the value that is transmitted in post?

I have this sample
CODE HTML:
<form method="post" class="add-patient">
<div class="col-md-12">
<fieldset>
<label for="lastname">Phone<span class="star">*</span></label>
<input class="required-input _phone" id="primary_phone" type="text" name="phone" maxlength="10" value="<?php echo $prInfo->clinicphone; ?>" placeholder="1234567890">
</fieldset>
</div>
<div class="col-md-12">
<div class="pull-right" id="save-bottom-add">
<button type="Submit" id="btn-sub" class="btn btn-primary btn-save" onclick="DoSubmit()">Submit</button>
</div>
</div>
</form>
CODE JS:
function DoSubmit(){
var firstFormat = $("#primary_phone").val(); //ex format:(123) 123-1234
var lastFormat = firstFormat.replace(/\s/g, ''); //the new format should be: 123-123-1234
console.log(lastFormat);
return true;
}
What I want to do is transform the format text of an input before submit and pass it in the new format to POST
It is correct that we have chosen method?
What is the solution to transform this format?
Can you help me find a solution to this problem please?
Thanks in advance!
Something like this should get you on track
function DoSubmit(){
var firstFormat = $("#primary_phone").val(); //ex format:(123) 123-1234
var lastFormat = firstFormat.replace(/\D/g,"").replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'); //new format: 123-123-1234
console.log(lastFormat);
// also do any substitution of value(s) here
// Ex:- $("#primary_phone").val(lastFormat);
return true;
}
$(".add-patient").submit(function() {
DoSubmit();
});
.submit() is a shortcut for .on( "submit", handler ) in the first variation, and .trigger( "submit" ) in the third. See docs
UPDATE: Thanks #titus for pointing out about non-numeric chars.
See the updated code and this fiddle for demo.
Try this:
function DoSubmit(){
var firstFormat = $("#primary_phone").val(); //ex format:(123) 123-1234
//First, replace all non-numeric character then, replace all groups of 3 numbers (not the ending group) with the group itself fallowed by a line.
var lastFormat = firstFormat.replace(/\D/g, "").replace(/(\d{3}(?!$))/g,"$1-");
// Change the input's value to the new one.
$("#primary_phone").val(lastFormat);
return true;
}

Submit form with a multidimensional array from Javascript to PHP

i have a big form with lot of inputs.
Also i have a javascript multidimensional array. It's an array of custom objects, that they are adding and removing as a shopping cart .
The array is defined as a local JS variable.
When i submit the form, i need to pass the array too, and i don't know how to do it.
Here I leave an example, it's illustrative only , as my form and my classes are much more complex .
<SCRIPT LANGUAGE="JavaScript">
var itemList = [];
var CustomClass = function (id, description) {
this.id = id;
this.description = description;
};
function addItem(id, description)
{
var item = new CustomClass( id,description);
itemList.push(item);
}
</script>
<form method="post" action="formSave.php">
<input type="text" name="someInput1">
<input type="text" name="someInput2">
<input type="submit" value="Submit">
</form>
Thank you very much.
If you were set on using a form to submit your data, id make a hidden text input and use JSON.stringify(data) in your js and decode it on server with json_decode server side.
<input id = 'jsValueHolder' style = 'display:none'>
<script>
function loadJSDataBeforeSend(dataToSend){
document.getElementById("jsValueHolder").value = JSON.stringify(dataToSend);
}
loadJSDataBeforeSend(itemList);
</script>
And on server side:
<?php
/* other code */
$jsonDataString = ... // get your data from the input
$dataObject = json_decode($jsonDataString);
$dataKeyValueArray = json_decode($jsonDataString, true);
?>
Note how adding true to the json_decode function returns a key value array rather than a php object.

How do I pass Bootstrap-tags input as an array to a form?

I need to pass an array to a form based on what is returned from bootstrap-tags input. I have followed the documentation to try and retrieve the array using the following code:
<form>
<input type="text" name = "language" value="Javascript,Ruby" id = "languages" data-role="tagsinput" />
<input type='hidden' name='languages_hidden[]' id = "languages_hidden" value='' />
<input name="save" onclick="mySubmit()" type="submit" value="Save">
</form>
<script>
function mySubmit() {
document.getElementById('skills_hidden').value = $("#skills").tagsinput('items')
}
</script>
I expect the resulting array that is passed on to be in the format when I click the submit button:
["Javascript", "Ruby"]
However, I see that that is actually how the array is passed on:
["Javascript, Ruby"]
How do i rectify this?
Change the function to the following. Also added a fall back just in case.
function mySubmit() {
document.getElementById('skills_hidden').value = ($("#skills").tagsinput('items') || [''])[0].split(', ');
}
Edit: Updated function to reflect returning of an array.

javascript print array values dynamic

hi everyone i have a problem in javascript i can print array if fix them in html but whn i try to print them on clic they are not working just print the array names
if i print seriesre simple it print values that is fine but when i check any checkbox and want to print one or tow of them it just showing array name not values
thanks for help
check this example
$(document).ready(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre= [Comment,WallPost,Likes];
var mygraphs = new Array();
alert(seriesre);
$("#testCheck").click(function() {
i=0;
$("#testCheck :checked").each(function() {
mygraphs[i]= $(this).val();
i++;
});
newseriesre = "["+mygraphs+"]";
alert(newseriesre);
});
});
<div class="activity">
<form method="POST" id="testCheck" name="myform">
Likes
<input type="checkbox" value="Likes" name="box2">
Comments
<input type="checkbox" value="Comment" name="box3">
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</form>
</div>
You can use
alert(myarray.join())
to alert your array's values
You should use a associative array instead of an array, so that you can look up the data based on the name as a string instead of trying to find the variable. All objects in Javascript are associative arrays, so just put the data in an object.
Also:
Create the mygraphs array inside the event handler, otherwise it can not shrink when you uncheck options.
Catch the click on the checkboxes inside the form, not on the form itself.
Put a label tag around the checkbox and it's label, that way the label is also clickable.
You don't need an index variable to put values in the mygraphs array, just use the push method to add items to it.
http://jsfiddle.net/cCukJ/
Javascript:
$(function() {
Comment = [['2011-01-29',7695],['2011-02-02',19805]];
WallPost = [['2011-01-29',11115],['2011-02-02',8680]];
Likes = [['2011-01-29',5405],['2011-02-02',10930]];
var seriesre = {
'Comment': Comment,
'WallPost': WallPost,
'Likes': Likes
};
$("#testCheck :checkbox").click(function() {
var mygraphs = [];
$("#testCheck :checked").each(function() {
mygraphs.push(seriesre[$(this).val()]);
});
alert("["+mygraphs+"]");
});
});
HTML:
<div class="activity">
<form method="POST" id="testCheck" name="myform">
<label>
Likes
<input type="checkbox" value="Likes" name="box2">
</label>
<label>
Comments
<input type="checkbox" value="Comment" name="box3">
</label>
<label>
Wall Post
<input type="checkbox" value="WallPost" name="box4">
</label>
</form>
</div>
I understand that you want to alert the selected values when clicking anywhere on the form? If that's true correct code with minimal changes to your existing code will be:
var mygraphs = [];
$("#testCheck").click(function() {
$("#testCheck :checked").each(function() {
mygraphs.push($(this).val());
});
alert("Selected values are: " + mygraphs.join(", "));
});
You can try this.
alert($("#testCheck :checked")
.map( function(i, field) { return field.value}
).get());
Check your working example in http://jsfiddle.net/dharnishr/d37Gn/

Categories