I have the following DOM structure:
<form>
<input type="text" id="a">
<button>Submit</button>
</form>
or:
<form>
<input type="text" id="a">
</form>
which one depends on what user have done, it's created dynamically.
I want to be able to add another input right below the previous one (it can not exist yet and be the first one). To do that, I wanna get all text until the place I'm adding new input. How can I get that text using regex?
I tried the following:
'(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]'
But it doesn't work, because it displays empty string as a result.
var afterRegex = new RegExp('(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]', 'i');
var appendAfter = $(".downloadCode textarea").val().match(afterRegex)[1];
alert(appendAfter);
I'm a little confused by your code, but, based on what you've said (and that you've tagged your question with jQuery), I think that you can accomplish what you are trying to do with this code:
var $newInput = **CREATE_YOUR_NEW_INPUT_ELEMENT_HERE**;
var $form = $("form");
var $lastInput = $form.find("input:last");
// no inputs, make the new input the first element in the form
if ($lastInput.length < 1) {
$form.prepend($newInput);
}
// at least on existing input, add the new input after the last one
else {
$lastInput.after($newInput);
}
You should not parse HTML using Regexp. No, seriously.
That being said, the correct syntax for multi-character alternatives is (?:alternativeA|alternativeB):
(.*?)(?:<button.*?>Submit<\/button><\/form>|<\/form>)
Note that this does not work if you have whitespace characters in between. Yet another reason not to use Regexps here.
Related
So I have this search, example I have this in my table "Test Building" and I can only search the first part of the name and its case sensitive like I input Test but I cant search if I type Building which is my problem so how do I correct this? here's what I did..
building.blade.php
<center>
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" id="search-building" class="form-control" placeholder="Search..." required>
<span class="input-group-btn">
</span>
</div>
</center>
<script type="text/javascript">
$("body").on("input", "#search-building", function() {
var text_filter = $(this).val();
var tr = $('tr');
$("table").find("tbody").find("tr").hide();
$("table").find("td").show();
$("table").find("tbody").find("tr:contains("+text_filter+")").show();
});
</script>
You could try:
var text_filter = $(this).val().toLowerCase()
Then it will always be lowercase.
I'm not sure if there's a nice jQuery-ish way to do that, but here's what I thought about.
You want a simple thing: find all trs in your table's body that contain some text. Text should be treated case-insensitively, so the tr:contains(...) doesn't work for you. There's nothing on the documentation saying we can make it case insensitive. So let's implement our own version!
It's quite simple: instead of using find, you want to get a list of all children of your tbody element and then filter them (which means you will take out those don't match the criteria). The criterion will be a case-insensitive RegExp.
Instead of this line:
$("table").find("tbody").find("tr:contains("+text_filter+")").show();`
Try doing this:
function matchesText (index, element) {
const regexp = new RegExp(text_filter, 'i')
return element.text().match(regexp)
}
$("table").find("tbody").children().filter(matchesText)
If you're not familiar with filter, please read about it here. It is a very ubiquitous concept now, when people heavily use functional programming.
I haven't tested this but it should work. The essence is creating a new regexp passing it the text and 'i' flag, which means "become case-insensitive". If you don't know how regular expressions work, please search the internet for it. Here we don't use any of complex concepts from RegExp world.
Again, we could do the same by just matching the case of both strings. Say, making both of them lowercase, like that: text_filter.toLowerCase().
I am trying to get a multiplication entered in an input replaced by its solution.
Basicaly, when you enter 3*3 into the input, I would like my javascript code to replace 3*3 by 9.
Probably not so hard to obtain but I'm a total noob with javascript here. I get this so far, but I should miss a crucial point!
Thanks for your help :)
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = Number(array[0]*array[1]);
document.getElementById("res").value = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <input type="text" id="res" readonly>
Your code actually works as it is now. Just make sure you tab out of the input field after typing in the equation and you'll see it do its job. That's because your code is running on the blur event, which is when the focus leaves an element.
But, as far as your conversion code goes:
Number(array[0]*array[1])
Attempts to convert the product of array[0] and array[1], when what you need is to convert each array value to a number first and then do the math.
Number(array[0]) * Number(array[1])
Now, instead of Number(), you can just prepend a + to each value that needs conversion.
+array[0] * +array[1]
But, in reality, anytime you attempt to do multiplication, division or subtraction on strings, they are automatically converted to numbers, so you really don't even need that here.
Lastly, since you are just displaying the result and don't want the user to be able to modify it, just put it into a regular element, like a span instead of a form field element that you then have to set to readonly. Form fields are primarily for collecting information, not displaying it. When you do work with a non-form field element, you don't use the value property, you use .textContent (when there is straight text) or .innerHTML (when the string contains HTML to be parsed).
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = array[0] * array[1];
document.getElementById("res").textContent = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <span id="res"></span>
what I have is 3 text boxes. The first one a user enters a string. The second box they enter part of the first string they want to replace. The third text box is the string that is to do the replacing.
I'm trying to use the replace() method but I dont think Im using it right or i should be using something else.
html:
<form>
Enter a string:<input type="text" id="user_string"><br>
Enter portion of previous string to be replaced: <input type="text" id="replace_string"><br>
Enter new string: <input type="text" id="add_string"><br>
<input type="button" value="Execute" onclick="BaitAndSwitch()"><br>
Result: <input type="text" id="req_4_results"><br>
</form>
Javascript:
function BaitAndSwitch(){
// create variables for the user entered data
var UserString = document.getElementById("user_string").value;
var ReplaceString = document.getElementById("replace_string").value;
var AddString = document.getElementById("add_string").value;
var Results = UserString.replace(ReplaceString, Addstring);
if (UserString.indexOf(ReplaceString) > -1) {
Document.getElementById("req_4_results").value = Results;
}
else{
alert("Something went wrong! Please check the data you entered.")
}
}
I know I'm doing something wrong. Maybe the use of variables in the .replace() method? Or maybe the if... using indexOf line?
I was essentially trying to set it up where it would check UserString with the value of ReplaceString and if it matched, it would then execute the replace() method and show results to the given HTML element. Else if the ReplaceString didn't match any thing from UserString, it would alert the user something was wrong and to check it.
JavaScript is cAsE SeNsItIvE. Please note that Document is not the same as the document object. Please use the below line:
document.getElementById("req_4_results").value = Results;
Oh and yes, as pointed out by blex, you have another typo too:
var Results = UserString.replace(ReplaceString, Addstring);
//-------------------------------------------------^ should be S
More Info: In the console, if you try both, see the result you get:
typeof Document
// "function"
typeof document
// "object"
On a side note, please do not use such Naming Conventions. Looks like you are migrating from Visual Basic.
Note that the replace() method does not modify the string that you call it on.
In your line of code:
var Results = UserString.replace(ReplaceString, Addstring);
The value of UserString will not changed as a result of having called replace() on it.
In your conditional statement:
UserString.indexOf(ReplaceString) > -1
If it is true, it means that UserString still contains at least one instance of ReplaceString within it.
That makes sense, because you wouldn't have modified UserString yet. If you want to make sure that Results no longer has any occurrence of ReplaceString, then you want to throw an error only if the following condition is true:
Results.indexOf(ReplaceString) > -1
I am checking and validating the text area value with a regex
and I want to change the formating like this:
user input:
123456
change to:
12/34/56
can this be done in pure js?
edit:
this is what I did yet:
function changeIt() {
var inputChanger = document.getElementById("id").value.replace(something , something);
document.getElementById("id").value = inputChanger;
}
but no idea how to proceed
Try something like this:
Note: for this code to work, the HTML must come before the JavaScript, but stack overflow apparently re-order's code snippets to always show the JS first (?)
var input = document.getElementById('my-input');
function format() {
// \d matches a digit,
// parenthesis let you use the matched values as $n in the replacement string
input.value = input.value.replace(/(\d\d)(\d\d)(\d\d)/, '$1/$2/$3');
}
// you probably only need one of these, but it doesn't hurt to have both
input.addEventListener('change', format);
input.addEventListener('keyup', format);
<input type="text" id="my-input" />
It can also, of course, be done with some jQuery and maybe a plugin like http://jquery-plugins.net/maskjs-jquery-plugin-to-mask-inputs - but I think it's good to understand what's happening under the hood even if you end up going that way.
I have some text on a page and I want to located and remove any text found in brackets.
For example:
<td>here is [my text] that I want to look at</td>
So I want to grab that text (my text), save it in a variable and remove it from where it is.
If you're using jQuery you could use a regular expression like \[(.+)\] on $('body').text().
EDIT: Sorry, I might have jumped the gun a little bit giving you this answer. Going to think about it for a few more minutes and try to update this with a little more info.
You may find that this task is not all that simple. If you have control over the text before it is sent to the web browser you may want to put a <span class='bracket'>[my text]</span> around the text, then you could easily do something like this with jQuery:
$(".bracket").each(function() {
// store the data from $(this).text();
}).remove();
This can be done using regular expressions and jQuery, but there are problems that may creep up dealing with text inside of attributes like <input name='test[one][]' /> The "simple" regex would be to do something like this:
$("td").each(function() {
var $this = $(this);
var html = $this.html();
var bracketText = [];
// match all bracketed text in the html - replace with an empty string
// but push the text on to the array.
html = html.replace(/\[([^\]]+)\]/g, function() {
bracketText.push(arguments[1]);
return "";
});
// put the new html in away and save the data for later
$this.html(html).data("bracketText", bracketText);
});
There is not much danger in doing this if you're sure you wont have [] inside of tags other than in the text.
I ended up doing the following:
$('#formQuizAnswers td.question').each(function(){
var header = $(this).text().match(/-.*-/);
$(this).text($(this).text().replace(header,''));
});
I changed my text I search for to have dashes around it IE -My text-