Should I be using replace() method? - javascript

I am a total noob to javascript and need some direction.
I am trying to do the following:
Create 3 text boxes:
User enters a string in the first text box.
User enters string to be replaced (part of the first string) in the second text box.
User enters new string to insert in third text box.
Button – calls a function to perform the replacement and displays the results in all uppercase.
I am using document.querySelector("myID").value; to grab the value entered, but i am not sure if i should be using replace() for this. Or if the variable needs to be converted to something else. (very confused)
If anyone could point me in the right direction it would be much appreciated.

You could use something like this:
<body>
<textarea id="textArea" ></textarea><br>
<input id="input1" /><br>
<input id="input2" /><br>
<input type="button" value="Replace" onclick="doReplace()" />
<div id="output">OUTPUT!</div>
<script>
function doReplace() {
var getById = document.getElementById.bind(document);
var get = function(id) { return getById(id).value };
var text = get('textArea'),
input1 = get('input1'),
input2 = get('input2'),
div = getById('output');
var regex = new RegExp(input1, "g"); // to replace globally you need this!
div.innerHTML = text.replace(regex, input2).toUpperCase();
}
</script>
</body>
EDIT:
jsfiddle.net

Javascript by default recognizes everything as string, when given a string operation. In this case you could use replace() method directly without any conversions.

Related

How can I retrieve an HTML form value and put it in a JavaScript object?

so I'm kind of a beginner at JavaScript and APIs, things like that. I want to implement an API into my website that can detect whether an article is fake news or not based on the title. I already found the API, which is this, but I'm a bit confused with how to retrieve the form value from my HTML code, shown below:
<input type="text" name="check" id="check">
<button onClick="checkFakeNews" id="btn">Check</button>
<p id="result"></p>
I already tried typing up this function:
function checkFakeNews() {
document.getElementById('check') = text
console.log(text)
}
to try to print out the value, but I didn't get anything.
I also want to get the result, stored in 'data' in the API I believe, and display it in the paragraph. I'd be very grateful to anyone who can help me!
Firstly, You are you writing document.getElementById('check') = text which doesn't do anything.
Second thing that in HTML onClick need to be equal to Function Call you are passing just the Name. You need checkFakeNews() instead of checkFakeNews
This should work as required.
function checkFakeNews() {
const input = document.getElementById('check');
const text = check.value;
console.log(text);
}
<input type="text" name="check" id="check">
<button onClick="checkFakeNews()" id="btn">Check</button>
<p id="result"></p>
https://www.javatpoint.com/document-getElementById()-method , and see https://www.w3schools.com/jsref/prop_text_value.asp
var s = document.getElementById("element").innerHTML; //to set
document.getElementById("myText").value = "Johnny Bravo"; to set

(VB) Passing a textbox value with a Url.Action via javascript

In VB, I am working on an MVC project. I have a text box to enter some search criteria, and a button next to it that upon pressing will submit the value of the text box. Html Snippet:
<input type="text" id="mySearchField" />
<button onclick="location.href='#Url.Action("Search", "Movies", New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'">Search</button>
My question revolves around the final part:
New RouteValueDictionary(New With {.searchCriteria = document.getElementById('mySearchField') }))'"
The code above does not work or compile, but this is my general idea of what I am attemping to do.
I want to pass the value of the text box along into the Movies/Search function, however I am at a loss as to how to format the line to mix the html, asp, and javascript all at once.
My VB Function for clarity:
Function Search(searchCriteria As String) As ActionResult
Return View()
End Function
Any advice is much appreciated!
This should be pretty close. This has jQuery as a prerequisite. To make this maintainable (you can do this, or not), I'd use NewtonSoft.Json to serialize the URL to Javascript properly, and url-encode the text box value.
<input type="text" id="mySearchField" />
<button id=myButton>Search</button>
<script>
var url = '#Html.Raw(Url.Action("Search", "Movies"))';
$("#myButton").click(function(){
location.href = url + '?searchCriteria=' + $("#mySearchField").val()
});
</script>

angularjs removing special characters in dynamic form elements

I am trying to use angularjs dynamic form elements but when I type something in inputs, there are appearing many special characters []"": and field, value .etc in textarea, I just want to see in textarea what I wrote in inputs ,
this is what I am working on it http://plnkr.co/edit/JbjqjAoQ3odBhXF1a13r?p=preview
sorry for my poor english,,,
What Chris Story says is correct. You are trying to model the text value of the <textarea> to an array of objects, inputs
If you are just trying to display the results like it seems, a <textarea> is not the way to go. You can display them in a simple list, like this:
<ul>
<li ng-repeat="input in inputs">{{input.field}} = {{input.value}}</li>
</ul>
EDIT
To display it in a <textarea>, you will need to store the list as string to use. This can be done by appending each item into a single string each time there is a change to an input value using ng-change.
Change the inputs to utilize the ng-change:
<div ng-repeat="input in inputs">
<input type="text" ng-model="input.field" ng-change="inputChanged()" />
<input type="text" ng-model="input.value" ng-change="inputChanged()" />
<button ng-click="removeInput($index); inputChanged()">Remove</button>
</div>
And create the function that is called to maintain the string:
$scope.inputChanged = function() {
$scope.listString = "";
for(var i = 0; i < $scope.inputs.length; i++) {
var field = $scope.inputs[i].field;
var value = $scope.inputs[i].value;
$scope.listString += field + " = " + value + "; ";
}
}
And finally, use this $scope.listString in the <textarea>:
<textarea rows="22" cols="55" ng-model="listString"></textarea>
I have forked your Plunkr here
The behavior does not make much sense from a UX perspective, but this seems to match your requirement. An option that might make sense is to add disabled="true" to the <textarea> so it can not be edited.
The issue is that you are rendering {{inputs}} and inputs is an Array.

How to pull an ID from a link the User inputted

HTML:
<body>
<input type="text" id="userINPUT" />
<button onclick="updatev1()">Submit</button>
<div id="video1">
</div>
<div id="video2">
</div>
</body>
The html has two divs, and an input text box,and of course, a submit button. What the user is supposed to do is enter a youtube link into the text box, and submit it.
JavaScript:
var userIN1 = document.getElementById("userINPUT");
var userIN2 = userIN1.value;
var index = userIN2.substring(string.indexOf('=') -1);
alert(index);
Now what I want the JavaScript to do is to grab the youtube link, and pull the ID from said link.
EX. The user inputs the link. 'http://www.youtube.com/watch?v=-K7lEFmFcKs', then the JavaScript would take the link and grab '-K7lEFmFcK' and store it in a variable for later use.
'userIN2' would be the variable that would store the user input value, and 'index' would take the whole ID coming after the '=' symbol of the link and store it.
I know this is considered a small task, but any help would be great.
Thanks!
Oh, and I heard these things can be done A LOT easier with jQuery. Should I use jQuery instead?
Sure should. It'd be that simple:
$('button').click(function() {
var userIN2 = $('#userINPUT').val();
var index = userIN2.split('=');
index = index[1];
});
This collects everything after v=
http://jsfiddle.net/7aZqB/4/
function getID(str) {
return str.substring(str.indexOf('=') -1).replace('v=', '');
}

How to change HTML between 2 delimiters?

Imagine the following scenario: I have this HTML body (this is just one example, the delimiters will be configurable by 3rd parties, so no way to use DOM methods like getElementBy...) :
<div id="login">
<form method="post" action="https://site.com/login.html?skin=webmail" id="fWM">
<fieldset>
<p><label>Login<br><input type="text" class="inpText" name="user" id="user"/> </label><span class="provider">#isp.com</span></p>
<p><label>Password<br><input type="password" class="inpText inpPass" name="pass" id="pass"/></label></p>
</fieldset>
<p id="forgot">
Forgot password? <span class="pipe">|</span>
Help
</p>
<br><a><input type="submit" value="" id="bOK"/></a></p>
</form>
Ok, this is just a part of some html body asking for Login and Password. As you can see, I have
< fieldset > and < /fieldset > and for this example those are my delimiters. This mean, everything between this delimiters I want to change for another html code. I have some 'begin of code' like this to you have some idea about what I'm talking:
var myBody = document.body.innerHTML;
var beginInject = myBody.indexOf("<fieldset>");
var endInject = myBody.indexOf("</fieldset>");
var InjectBody = 'Hello World!';
//what to do now to put Hello World! between the <fieldset> and </fieldset>??
Remember this is just one example, I can need to put the delimiters like < body> and < /body> or something like: "Click Here to Start download" and "Thank you for visiting this website"... What I mean is: can be anything inside the body, and between the 2 delimiters I want to put my HTML code. Thank you.
If you insist to make it your way, use
var beginText = "<p>",
endText = "</p>",
injectText = 'Hello World!';
var html = document.body.innerHTML,
beginPos = html.indexOf(beginText),
endPos = html.indexOf(endText);
document.body.innerHTML =
html.substring(0, beginPos + beginText.length)
+injectText
+html.substring(endPos + endText.length);
Demo
But be aware that this way
You will remove all event listeners inside your body
You will lose all element's properties (not attributes)
Browser will reload all body (slow)
And it won't work on all cases. For example:
If you search for <p>, you won't match <p class="myClass">
If you search for <p a="b" c="d">, you won't match <p c="d" a="b">
Text could be matched instead of real elements, for example if text appears in a textarea.
endPos could be smaller than beginPos, for example because it appears in a textarea.
The problem is that You can't parse [X]HTML with regex because Zalgo is coming, so it's even worse to parse it with just text.
You could use document.querySelector.
For example:
document.querySelector('#login fieldset');
And its argument can be the selector that you want. This way you don't have to worry if you are matching by id, by class, by tagname, by name, etc.

Categories