I've searched quite a bit for this, but to no avail. I'm trying to make my input box start with a "#". It cannot just be a <span>#</span>, it needs to be in the input box itself. Is there no way of doing this?
You can also do this on the client side with a bit of javascript
function addHash(elem) {
var val = elem.value;
if(!val.match(/^#/)) {
elem.value = "#" + val;
}
}
and the HTML
<input type="text" onkeyup="addHash(this)"/>
Every time the user enters a character into the textbox, addHash would check if the first character is a hash, and if it isn't, then adds the hash mark.
If you want to check this server-side, since users can and probably will erase it:
function prependHash($string) {
if(substr($string, 0, 1) === "#") { return $string }
else return "#" . $string;
}
Relevant HTML:
<input type="text" name="someInput" value="#">
Relevant PHP:
//just in case they erase the hash:
$hashedValue = prependHash($_POST['someInput']);
Related
In the below, when a user changes the Asset Tag, I want what they entered to be added to the end of the field to the left (hostname) if and only if the hostname currently has a value that ends in '-'.
Also, I don't know the exact ID or name or either of these two inputs as they're generated in PHP like this:
<input type="text" name="hostname-<?=$t;?>" class="form-control" id="hostname-<?=$t;?>">
<input type="text" name="asset-tag-<?=$t;?>" class="form-control" id="asset-tag-<?=$t;?>">
How can I achieve this?
EDIT - I ended up achieving what I wanted with this code (as asset-tag and hostname always share the last digit:
$("[name^='asset-tag']").on("change", function () {
var host = $(this).attr('name');
var hostname = $('#hostname-' + host.substr(host.lastIndexOf("-") + 1));
var host = hostname.val();
if (host.slice(-1) == "-") {
hostname.val(host = host + $(this).val());
}
});
Basically you need:
$("[name^='asset-tag']").on("change", function () {
var $host = $(this).prev("[name^='hostname']");
if ($host.val().substr($host.val().length-1) == "-") {
$host.val($host.val()+$(this).val());
}
});
Where [name^= means "the name attribute starts with".
Note: This assumes that the host is the closest element which has a name which starts with hostname.
I want this jQuery to only fire after actual text (not something like a backspace or tab is pressed) is inputted into the search bar, so that not all the possible search results will display from my database.
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("search.php",{searchVal:searchTxt,}, function(output) {
$("#output").html(output);
});
}
Here is the input:
<input id='input' type="text" name="search" placeholder="Search Here..." onkeydown="searchq();" autocomplete="off">
Just add an if condition based off of the results of trim:
if(searchTxt.trim() != '') {
// do your post
trim will remove whitespace from both ends of the string. If a tab or a space is the only thing in the value, the result of trim will be an empty string.
As #Karl-André Gagnon pointed out in his comment, there is also a jQuery-specific function you can use to trim whitespace:
if($.trim(searchTxt) != '') {
Test whether the input is not empty
if (searchText != '') {
...
}
I have a live search on a site I'm developing. At the moment, it searches the MySql database after the first character is typed, and updates the search for each new character. When Space is pressed as the first character, it displays all entries in the database. I don't want it to do that. I have the following code that I found somewhere that prevents the SPACE character from being typed:
$('input[type="text"]').keydown(function(e){
var ignore_key_codes = [8,32];
if ($.inArray(e.keyCode, ignore_key_codes) >= 0){
e.preventDefault();
}
});
This does what it's meant to do, but not exactly what I want. This will prevent the space bar from working in the text input at all, what I require is that it only prevents the space bar if it's the first character being typed. For example, typing " apples" would prevent the space, but typing "apples oranges" wouldn't.
Is there anything I can try to achieve this?
You can do it easily like this example:
function keyPress(e) {
var e = window.event || e;
var key = e.keyCode;
//space pressed
if (key == 32) { //space
return;
}
searchInDataBase(); //make your ajax call to search in data base etc.
}
If the space key is pressed, you return and dont do nothing, otherwise you continue in your search...
$('input[type="text"]').keydown(function(e){
if (e.keyCode == 32 && $.trim($(this).val()) == ''){
e.preventDefault();
} else {
alert("searching..");
}
});
Demo: http://jsfiddle.net/BerkerYuceer/JJG9M/
Following on from #Florent's comment, when a user types a value into your textbox,check if the trimmed value is != '' if so it should be safe to continue
e.g
if($.trim($txtbox.val()) != ''){ // proceed to do search
}
I have a web form, and I'd want the user while filling the form to not include any Chinese single quotes/double quotes in a textarea, how can I do that ?
You could get the form content and check it against a list of non accepted characters:
$formContent = $_GET["formcontent"];
$badCharacters = array("'", "‘", "“");
$cleanResult = str_replace($badCharacters, "", $formContent);
The bad characters array has the quote signs you dont like (if they are the standard quotes you will need to escape them) then the str_replace function goes through the form data replacing each one with an empty string. You should do proper escaping and security before this of course.
To prevent user from typing into form element you must use client side scripting aka JavaScript.
Simple way is handling the onkeypress event:
<textarea onkeypress="return CheckKey(event);"></textarea>
And having such code:
var arrForbiddenCodes = [97, 98, 99];
function CheckKey(event) {
var keyCode = event.keyCode || event.which;
for (var i = 0; i < arrForbiddenCodes.length; i++) {
if (arrForbiddenCodes[i] === keyCode)
return false;
}
return true;
}
This will block characters based on their key code - in the above code, the lower case "a", "b" and "c" letters will be blocked. To find key code of specific character, add alert(keyCode); to the function and just type that character into the textarea.
Live test case.
you could add some javascript that uses a regex to restrict the entry to alpha or alpha and numeric (or any additional characters you want).
<script language="javascript">
function blockChar()
{
var str = document.getElementById('txt').value;
if(str.match(^[a-zA-Z0-9]*$)) {
return true;
}
else {
return false;
}
}
</script>
Currently, when someone just hits the space key and hits enter it will go to the next page but not search anything - I want to prevent the search altogether. What is the best way to accomplish this? I don't want to prevent spaces from being used (ie: How do I fix this?) - I just dont want spaces themselves to allow a search.
Wrap your query variable in an empty condition:
if(!empty(trim($_POST['searchterm']))
{
// do search
}
Use JavaScript and trim leading spaces in the submit (onsubmit) event handler:
var searchField = document.getElementById('search'); // or whatever the id of the field is
if(searchField.value.replace(/^\s+/, '').length === 0) {
return false; // or evt.preventDefault().
}
It should be okay to rely on client-side validation here because if the user wants to fool the search engine then they won't mind being brought to a blank page. If there's an actual server-side problem in allowing this, then perform the same check server-side:
if(!isset($_REQUEST['search']) || !trim($_REQUEST['search'])) {
// Don't perform the search
}
In addition to #AlienWebguy answer you can use JavaScript to do client side validation in order to stop the page from even getting to the back end. Its definitely a good practice to do the validation on the client side AND server side.
Live Demo
form.onsubmit = function(){
if(input.value.replace(/^\s/,"").length === 0){
return false;
}
}
Just take the string, trim the initial and final spaces and check the length; if length is 0, don't submit the form.
If you are procecssing it with php on the backend you can just use trim($input), but for a better user experince use javascript. Set a form validator so it won't submit unless there is something other than whitespace.
<form onsubmit="return verify()">
<input id="foo" name="foo" />
<input type="submit" />c
</form>
<script type="text/javascript">
function verify() {
if (document.getElementById("foo").value.match(/[^\s]/) == null) {
alert('only whitespace');
return false;
} else {
alert('found substance');
return true;
}
}
</script>