I want the string 'Surveillance Capitalism' to be inputted letter by letter into a text input (or something that looks like one) as a user types.
The code works up to the point I try to add the letter into the input, at which point I am told 'Failed prop type: You provided a value prop to a form field without an onChange handler'. Is this method possible? If not what is a good alternative?
Html:
<input
id="search-bar"
type="text"
onKeyPress={this.handleKeyPress}
/>
JS:
//Dictates what is typed in the search bar
(https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs)
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
//Converts firstSearchString into an array of its members (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
var searchStringArray = Array.from(firstSearchString);
//Gets contents of search bar
var searchBar = document.getElementById("search-bar").value;
//Length of that content
var i = searchBar.length;
searchBar.value += searchStringArray[i];
};
Essentially I want to trick the user into thinking they can search whatever they want but when they go to type, my preset query will be entered letter by letter.
The problem is that you are assigning a variable to the search bar:
var searchBar = document.getElementById("search-bar").value;
then altering the variable, to fix your problem i just did this:
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
var searchStringArray = Array.from(firstSearchString);
for(let i = 0; i < searchStringArray.length; i++) {
document.getElementById("search-bar").value += searchStringArray[i];
}
};
I think that's what you were having trouble with but i'm not sure if i understood the question. I hope this helped
Try the onChange event handler, rather than the onKeyPress handler. That should remove the error you have. They are functionally slightly different, but should accomplish the same thing.
Related
I have multiple forms that are using Google Autocomplete on the same page. A bit of context on how the page works: Users can basically add how many steps they want (to add a step, the form uses the Google Autocomplete), and inside each step they can add activities (to add an activity, the form uses also the Google Autocomplete).
I know that by assigning different ids to each form, then getting the element by Id to apply the autocomplete and get the data, would work, but the problem is that each time a user creates a step, it creates a step id, and then an activity form will be assigned to a specific step id, which makes it challenging as in the end I can end up having a lot of different ids.
That's why I was trying a different approach through class instead of id. So let's say I have those 2 forms. They have both the "search_term" class:
<input type="text" class="form-control search_term" placeholder="Search...">
<input type="text" class="form-control search_term" placeholder="Search...">
Then I have basically implemented a for loop so that the program can read all the items that have this class, and then for each item implement the autocomplete + get data about a specific place. The autocomplete works. But then I get "undefined" for the first item when trying to get the data.
<script>
function activatePlacesSearch(){
var input = document.getElementsByClassName('search_term');
var i;
for (i = 0; i < input.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(input[i])
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var result = autocomplete.getPlace();
console.log(result)
if (result != null) {
const location = result['name']
const name = result['name']
const address = result['formatted_address']
const phone_number = result['international_phone_number']
const icon = result['icon']
const types = result['types']
const user_ratings_total = result['user_ratings_total']
const rating = result['rating']
const url = result['website']
const latitude = autocomplete.getPlace().geometry.location.lat();
const longitude = autocomplete.getPlace().geometry.location.lng();
const photos = result['photos'][0].getUrl();
};
});
};
};
</script>
I am a bit stuck on how to solve that. Thanks a lot for your help.
This is just a wild guess, but i´m pretty sure by overwriting variable autocomplete you destroy functionality, maybe try to use dynamic variable-names for each autocomplete:
window['autocomplete_'+i] = new google.maps.places.Autocomplete(input[i])
...
var result = window['autocomplete_'+i].getPlace();
...
I am wondering if it is okay to put html dom references in js oop. Although there are many JS OOP tutorials online, I haven't seen anything similar to what I am referring to. The code below is what I am referring to.
var form = {
fname : document.getElementById("fname").value;
};
say, for example the document.getElementById("fname").value is a textbox with a value of "jacob". would form.fname = "jacob"?
is this okay to do? is this a common practice to do?
you can do it if the object was created after the load event so you can make sure that the element "fname" is initialized ...
for example...
$(document).ready(function(){
var form = {
fname : document.getElementById("fname").value;
};
});
if you dont want to use jQuery here is another example ...
window.addEvent('load',function(){
//your object ...
});
I am not sure what you're trying to accomplish here. If you only need to retrieve the value that is currently in the input field, one time, ever, then this ought to be fine. If you're expecting the value of form.fname to continually update when the input value changes, you're not going to see that happen. You'd either need some handler tied to the change event of the input, or you'd need to do something more like this:
var form = {
fname: function () {
return document.getElementById('fname').value;
}
};
// Retrieving
form.fname()
Note that you have to invoke the fname function now, you can't simply refer to it as form.fname.
If you really don't want to ever have to retype things ever, do something like this:
var fields = ['fname', 'lname', 'city', 'state'];
var form = {};
for (var i = 0, j = fields.length; i < j; ++i) {
form[fields[i]] = function () {
return document.getElementById(fields[i]).value;
}
}
You'll have to be a little bit more careful with that if you add things like dropdown lists to your form, because their .value isn't as helpful, but you don't retype names if one changes.
And, if we really want to be fancy about it, you don't even have to type names when you get the values:
for (var i = 0, j = fields.length; i < j; ++i) {
console.log(form[fields[i]]())
}
I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');
I noticed that some validation tools use the "class" attribute to pass options to validation scripts.
Example:
<input class="input-field validate[required, email]" name="" type="text" />
the "required" and "email" would be picked up by the script as setting options.
I was wondering is there an easy way to achieve this or maybe this is already available in jQuery?
I want to use this as a means of passing certain settings to my script.
Any help would be appreciated,
Thanks
Edit:
Thanks #loseb your example works great.
Another thing I am trying to achieve by doing some small modification to your example:
function classAttributes( classString, className ) {
var data;
var regex = new RegExp(className+"\[(.*?)\]");
var matches = classString.match(regex);
if ( matches ) {
//matches[1] refers to options inside [] "required, email, ..."
var spec = matches[1].split(/,\s*/);
if ( spec.length > 0 ) {
data = spec;
}
}
return data;
}
any idea why "new RegExp(className+"[(.*?)]");" doesnt work. var matches is blank.
Edit:
second part of the question moved to:
javascript regex pattern with a variable string not working
If I understand you correctly this is the solution:
var className = $('.input-field').att('class');
var regex = /validate\[(.*?)\]/;
var matches = className.match(regex);
if (matches) {
//matches[1] refers to "required, email" string
var spec = matches[1].split(/,\s*/);
if (spec.length == 2) {
var attribute = spec[0]; //required or optional or anything else
var validator = spec[1]; //actual validation type
}
}
I would just use data to do this instead:
var mydata={required: true,email:false};
$('.input-field').data('validate',mydata);
see an example here:http://jsfiddle.net/MarkSchultheiss/FzaA8/
I'm trying to write a order form that shows the value of the selected items automatically. The backend is already complete, and on the front end each field, all radio / checkbox, look like this:
<input type="radio" name="shirt-size" value="shirt_size_m[18]" />
'18' being the price, everything else being irrelevant to the front end price calculation. I cannot change the naming convention, so I need to get the value between the brackets on all the <input>s on the page (or below the parent ID), add them together (on update), and append the value to another ID. Jquery is already in use on the site if that makes thongs easier.
I just need to be pointed in the right direction as my JS experience is limited to examples and minor customizations :)
Try using a simple regular expression with Javascript's replace, to replace all non-numeric characters with the empty string:
var str = "shirt_size_m[18]";
var theNumber = parseInt(str.replace(/[^0-9]/g, ''));
alert(theNumber);
Demo: http://jsfiddle.net/XvTaY/1/
You could try something like this:
function calculate_sum(form_id) {
var $form = $(form_id);
var sum = 0;
$checkbox_and_radios = $form.find('input[type=checkbox], input[type=radio]').each(function(){
sum += parseInt($(this).val().match(/^[^\[]+\[(\d+)\]$/)[1]);
});
return sum;
}
$(function(){
$("#id_of_the_form").find('input[type=checkbox], input[type=radio]').change(function(){
var sum = calculate_sum("#form_id");
// I don't know the type of your element containing
// the sum, so I put multiple solutions here:
// some input element
$('#another_id').val(sum);
// or another element
$('#another_id').html(sum);
// I'm assuming you don't really mean append
// If you're sure you want to append: (but then the old value won't be deleted)
$('#another_id').append(sum);
});
});
u can use:
var v;
v = $('#input-identifier').val();
v = v.split("[");
v = v[1];
v = v.split("]");
v = v[0];
// now v has the number